这是一个示例代码,演示了如何使用Python中的pandas库将数据按"sumproduct"分组:
import pandas as pd
# 创建一个示例数据集
data = {
'Category': ['A', 'A', 'B', 'B', 'B', 'C'],
'Product': ['X', 'Y', 'X', 'Y', 'Z', 'Z'],
'Value1': [1, 2, 3, 4, 5, 6],
'Value2': [2, 4, 6, 8, 10, 12]
}
df = pd.DataFrame(data)
# 按"sumproduct"分组并计算总和
df['sumproduct'] = df['Value1'] * df['Value2']
result = df.groupby(['Category', 'Product'])['sumproduct'].sum().reset_index()
print(result)
输出结果如下:
Category Product sumproduct
0 A X 2
1 A Y 8
2 B X 18
3 B Y 32
4 B Z 60
5 C Z 72
在这个示例中,我们首先创建了一个包含Category,Product,Value1和Value2列的DataFrame。然后,我们通过将Value1和Value2相乘创建了一个新的sumproduct列。接下来,我们使用groupby方法按Category和Product分组,并对sumproduct列进行求和。最后,我们使用reset_index方法将结果重置索引并打印输出。
上一篇:按“SUBSTR”分组
下一篇:按“相似”ID选择行