以下是Python Pandas库的代码示例:
import pandas as pd
# 创建示例数据
data = {'tenant': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A'],
'value': [0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1]}
# 转换为数据帧
df = pd.DataFrame(data)
# 在“tenant”列分组并计算连续的1的数量
temp = (df['value'].ne(df['value'].shift())
.cumsum()
.where(df['value'] == 1)
.value_counts())
# 找到最大值
max_consecutive_ones = temp.max()
# 输出结果
print("按列“tenant”分组,并获取“value”列中最大连续的1:", max_consecutive_ones)
输出结果为:
按列“tenant”分组,并获取“value”列中最大连续的1: 3
上一篇:按列特定类型分组