排名最高连续行,其中值为True

时间:2016-12-16 02:07:28

标签: python pandas numpy

我的问题与此处发布的问题非常相似:Determine mean value of ‘data’ where the highest number of CONTINUOUS cond=True

由@Divakar精心解决。但是,我的需求略有不同。而不是最高的最大值,我怎么能得到 - 排名第二,第三,等等排名?

一种解决方法是使用已经排名的值连续减少原始数组并迭代运行@Divakar解决方案,但我想知道是否有人有更有效的解决方案

2 个答案:

答案 0 :(得分:0)

而不是

res[res['count'] == res['count'].max()]

您可以使用

res[res['count'] == res['count'].sort_values().unique()[-n]]

对于你想要的任何n

答案 1 :(得分:0)

您需要为每组连续的行附加一个组号。一些棘手的逻辑将表明使用以下语句完成以下操作。该逻辑基于使用diff来查找每个出现1的前缀为0。

# create fake data
import pandas as pd
import numpy as np

np.random.seed(2)
df = pd.DataFrame({'cond':np.random.choice([True, False], 100), 
                   'data':np.random.rand(100)})

print(df.head(15))

     cond      data
0    True  0.544208
1   False  0.082095
2   False  0.366342
3    True  0.850851
4    True  0.406275
5   False  0.027202
6    True  0.247177
7   False  0.067144
8    True  0.993852
9   False  0.970580
10   True  0.800258
11  False  0.601817
12  False  0.764960
13  False  0.169225
14  False  0.293023

# add a group column
df['group'] = ((np.where(df.cond.diff() > 0, 1, 0) * df.cond).cumsum() +
                df.cond.iloc[0]) * df.cond

print(df.head())

     cond      data  group
0    True  0.544208      1
1   False  0.082095      0
2   False  0.366342      0
3    True  0.850851      2
4    True  0.406275      2
5   False  0.027202      0
6    True  0.247177      3
7   False  0.067144      0
8    True  0.993852      4
9   False  0.970580      0
10   True  0.800258      5
11  False  0.601817      0
12  False  0.764960      0
13  False  0.169225      0
14  False  0.293023      0

# get answer with grouping and sorting
df_final = df.query('group != 0').groupby('group')['data']\
                                 .agg(['count', 'mean'])\
                                 .sort_values('count', ascending=False)

print(df_final.head())
       count      mean
group                 
18        10  0.529819
11         8  0.630232
10         4  0.301558
16         4  0.215376
6          4  0.563013

# get result with .iloc
# if you care about ties you can select those rows that all have
# the third highest count
df.iloc[[2]]
       count      mean
group                 
10         4  0.301558
相关问题