可以使用pandas的groupby()函数对DataFrame数据进行分组聚合操作,实现按两列分组计算统计量的大小。 例如,对以下数据集按照“category”和“color”两个列进行分组,统计“price”的均值、标准差和数量:
import pandas as pd
data = pd.read_csv("data.csv")
result = data.groupby(["category", "color"]).agg({
"price": ["mean", "std", "count"]
})
print(result)
输出结果为:
price
mean std count
category color
A Black 21.000000 0.000000 1
Blue 16.666667 5.773503 3
B Brown 27.333333 1.247219 3
Red 22.500000 3.535534 2
其中,”mean”表示均值,“std”表示标准差,“count”表示数量。
上一篇:按两列分组后获取组之间的差异
下一篇:按两列分组行,并按比较筛选值。