python-3.x - 如何计算列中连续的1并获得每组的最大计数

标签 python-3.x pandas numpy pandas-groupby

我有包含“A”列和“标志”列的数据框。我想应用groupby函数并获得每组中连续1的最大计数

输入数据:

df=pd.DataFrame({'A':[1,1,1,1,1,1,2,2,2,2,2,2,2],'flag':[1,1,0,1,1,1,0,1,1,0,1,1,1]}) 

所需的输出

output= pd.DataFrame({'A':[1,1,1,1,1,1,2,2,2,2,2,2,2],'consective_count_max':[3,3,3,3,3,3,3,3,3,3,3,3,3]})  

最佳答案

IIUC,GroupBy.sumSeries.maxlevel=0。 我们可以使用Series.map使用原始索引创建一个系列:

blocks=df['flag'].ne(df['flag'].shift()).cumsum()
df['consecutive_count_max'] = (df['A'].map(df.groupby(['A',blocks])['flag']
                                             .sum()
                                             .max(level=0)))
print(df)

    A  flag  consecutive_count_max
0   1     1                      3
1   1     1                      3
2   1     0                      3
3   1     1                      3
4   1     1                      3
5   1     1                      3
6   2     0                      3
7   2     1                      3
8   2     1                      3
9   2     0                      3
10  2     1                      3
11  2     1                      3
12  2     1                      3

请注意,相加时,flag == 0 的组所得的总和永远不会大于 flag == 1 的组的总和,因此 df['flag '].eq(1) 不是必需的

如果flag不是1或0,则需要检查例如df['flag'].eq('yes')。我们可以使用:

mapper = pd.crosstab(df['flag'].ne(df['flag'].shift())
                               .cumsum()
                              .loc[df['flag'].eq(1)], df['A']).max()
df['consecituve_count_max'] = df['A'].map(mapper)
#print(df)

详情

print(df['flag'].ne(df['flag'].shift()).cumsum())

0     1
1     1
2     2
3     3
4     3
5     3
6     4
7     5
8     5
9     6
10    7
11    7
12    7
Name: flag, dtype: int64

关于python-3.x - 如何计算列中连续的1并获得每组的最大计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60928340/

相关文章:

python - 如何在 Pandas 中的后续行之间进行操作?

python - 找到pandas python中的特殊位置

python - 找到所有接近目标的值,如 numpy.searchsorted() 但返回所有相同的值?

python - 如何使用 NumPy 将 sRGB 格式转换为 NV12 格式?

python - 添加到由另一个数组索引的数组的矢量化方式 - Python/NumPy

python - 在 Django 中获取早于 10 天的数据库表数据

python - 准备循环中仅匹配的 json 键

python - 用 python 中的变量替换链式方法

Python - 有没有办法将 "as"别名添加到 for 循环?

python - 我的电报机器人出现 "SSL: CERTIFICATE_VERIFY_FAILED"错误