简体   繁体   English

Pandas 按连续数字分组

[英]Pandas group by consecutive numbers

I'm dealing with a DataFrame like this:我正在处理这样的 DataFrame:

n_days    probability
 0            0.01
 17           0.1
 18           0.11
 19           0.12
 40           0.2
 41           0.21

I want to group consecutive numbers and get the mean probability of each group, like this:我想对连续数字进行分组并获得每组的平均概率,如下所示:

n_days     mean_probability
  0           0.01
 17-19        0.11
 40-41        0.205

Formatting on the n_days isn't too relevant. n_days上的格式不太相关。

I tried something like:我试过类似的东西:

df['diff_days'] = df.n_days - df.n_days.shift()

And then:接着:

df.diff_days.eq(1)

Which brings this boolean:这带来了这个 boolean:

n_days    probability   bool_eq
 0            0.01       False
 17           0.1        False
 18           0.11       True
 19           0.12       True       
 40           0.2        False
 41           0.21       True

Which seems to be a step forward, but I'm not sure how to follow up.这似乎是一个进步,但我不知道如何跟进。 Each False would be the start of each group, but how would I catch the whole group?每个False将是每个组的开始,但我将如何抓住整个组? Any help would be appreciated.任何帮助,将不胜感激。 Thanks.谢谢。

You could use pd.cut + DataFrame.groupby :您可以使用pd.cut + DataFrame.groupby

mean_probability=df.groupby(pd.cut(df.n_days,len(df)//2)).probability.mean()

n_days
(-0.041, 13.667]    0.010
(13.667, 27.333]    0.110
(27.333, 41.0]      0.205
Name: probability, dtype: float64

You can group on pd.cut bins.您可以对pd.cut箱进行分组。 Note that each bin is from but excluding the first value to and including the last value, eg (16-19] is equivalent to [17-19] where the column consists of integers.请注意,每个 bin 从但不包括第一个值到最后一个值,例如 (16-19] 等价于 [17-19],其中列由整数组成。

bins = [-1, 0, 16, 19, 39, 41]
>>> df.groupby(
        pd.cut(df['n_days'], bins))['probability'].mean().dropna()
n_days
(-1, 0]     0.010
(16, 19]    0.110
(39, 41]    0.205
Name: probability, dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM