假设我有一个 df:
df = pd.DataFrame({'id': [12, 35, 37, 67, 99, 78],
'product': ['banana', 'apple', 'banana', 'pear', 'banana', 'apple'],
'reordered': [1, 0, 0, 1, 1, 1]})
id product reordered
0 12 banana 1
1 35 apple 0
2 37 banana 0
3 67 pear 1
4 99 banana 1
5 78 apple 1
我想计算“产品”列中产品出现的次数,以及按产品分组的“重新排序”列中的值。期望的结果:
product count reordered_0 reordered_1
0 banana 3 1 2
1 apple 2 1 1
2 pear 1 1 0
请多多指教
最佳答案
使用crosstab
与 DataFrame.insert
对于第一个位置的列:
df = pd.crosstab(df['product'], df.reordered).add_prefix('reordered_')
df.insert(0, 'count', df.sum(axis=1))
df = df.reset_index().rename_axis(None, axis=1)
print(df)
product count reordered_0 reordered_1
0 apple 2 1 1
1 banana 3 1 2
2 pear 1 0 1
关于Python:按组计算数据框中的特定事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67597093/