以下是一个使用Python的pandas库来按照两个维度进行分组并计数的示例代码:
import pandas as pd
# 创建示例数据
data = {'Category': ['A', 'A', 'B', 'B', 'B', 'C'],
'Color': ['Red', 'Blue', 'Red', 'Red', 'Blue', 'Blue']}
df = pd.DataFrame(data)
# 按照两个维度进行分组并计数
grouped = df.groupby(['Category', 'Color']).size().reset_index(name='Count')
# 打印结果
print(grouped)
运行以上代码,将输出如下结果:
Category Color Count
0 A Blue 1
1 A Red 1
2 B Blue 2
3 B Red 1
4 C Blue 1
以上代码首先使用pandas库创建一个包含"Category"和"Color"两个维度的数据表。然后使用groupby
函数按照这两个维度进行分组,并使用size
函数计算每个组的数量。最后,使用reset_index
函数将结果转换为一个新的DataFrame,并将计数列命名为"Count"。