私は次のようなデータフレームを持っています
customer fruit price
0 cust1 mango 30
1 cust2 apple 45
2 cust1 banana 55
3 cust3 mango 22
4 cust4 banana 54
5 cust3 apple 55
6 cust2 apple 90
7 cust1 mango 45
8 cust3 banana 45
9 cust2 mango 23
10 cust4 mango 44
必要なのは=各顧客がマンゴーや他の果物(つまり、カテゴリとしてのマンゴー自体ではない)の購入に費やした金額です。cust1 mango = 75、cust1 other = 55、各顧客にとって賢明です。
customer price spent_on_mango spent_on_others
0 cust1 75 55
1 cust2 23 135
2 cust3 22 100
3 cust4 44 54
提案してください。
果物がマンゴーかどうかを示す列を作成して、それを自分の中に含めてみgroupby
ませんか?
df['mango'] = df.fruit == 'mango'
df2 = df.groupby(['customer', 'mango']).sum().unstack()
df2.columns = ['not mango', 'mango']
>>> df2
not mango mango
customer
cust1 55 75
cust2 135 23
cust3 100 22
cust4 54 44
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加