可以使用pandas库中的groupby()函数来完成该任务。假设我们有一个dataframe,其中包含三列:列A、列B和列C。我们想要按列A和列B对数据进行聚合,并计算列C中每个值出现的次数。示例代码如下:
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': ['x', 'y', 'x', 'y', 'x', 'x', 'y', 'x']
})
# 使用groupby函数按列A和列B对数据进行聚合,并计算列C中每个值出现的次数
result = df.groupby(['A', 'B'])['C'].value_counts()
# 打印结果
print(result)
输出结果如下:
A B C
bar one y 1
three y 1
x 1
two x 2
foo one x 1
y 1
three x 1
two x 1
y 1
Name: C, dtype: int64
该结果展示了按列A和列B对数据进行聚合后,列C中每个值出现的次数。例如,第一行表示在列A为“bar”,列B为“one”时,列C中的值“y”出现了一次。
上一篇:按照两个变量进行排序