使用pandas库中的groupby函数来对数据框进行分组操作,然后通过对每个分组应用相应的聚合函数或转换函数,生成新的输出数据。
示例代码:
import pandas as pd
# 创建数据框
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
# 按A列值进行分组,并应用聚合函数sum()、mean()、count()和transform()分别操作B、C、D列
grouped = df.groupby('A').agg({'B': sum, 'C': 'mean', 'D': 'count'}).transform(lambda x: x / x.sum())
# 输出结果
print(grouped)
输出:
C D B
A
bar 0.454545 0.428571 0.428571
foo 0.545455 0.571429 0.571429
上述代码实现了对数据框按A列值进行分组,并对B、C、D列应用了sum()、mean()、count()和transform()函数。其中,agg()函数用于对分组后的数据进行聚合,transform()函数用于对各列进行变换操作。最后,通过计算每列数据占总和的比例,生成了新的输出数据。
上一篇:按列值分组并基于另一列值保留行
下一篇:按列值分组的 Antd 树形表