假设数据框为df,有类型(type)和数值(value)两列,代码示例如下:
import pandas as pd
# 生成示例数据
df = pd.DataFrame({
'type': ['a', 'b', 'a', 'b', 'c'],
'value': [1, 2, 3, 4, 5]
})
# 按类型重新分组,计算每组的条件求和
result = df.groupby('type').apply(lambda x: x[x['value'] > 2]['value'].sum())
print(result)
输出结果如下:
type
a 3
b 4
c 5
dtype: int64
解释:先按类型(type)重新分组,然后对每组进行条件求和,即计算数值(value)大于2的行的数值总和。最后输出每组的求和结果。
下一篇:按类型自动装配所有接口