【发布时间】:2023-02-13 14:17:53
【问题描述】:
我有这个数据框:
import pandas as pd
df = pd.DataFrame({"ID": ["123", "456", "123", "456", "123", "456", "456", "456", "456", "123"],
"number": [2,1,5,2,4,5,2,1,6,7],
"name": ["apple", "orange", "orange", "pear", "pear", "apple", "lemon", "apple", "lemon", "apple"]
})
ID number name
0 123 2 apple
1 456 1 orange
2 123 5 orange
3 456 2 pear
4 123 4 pear
5 456 5 apple
6 456 2 lemon
7 456 1 apple
8 456 6 lemon
9 123 7 apple
我想计算我命名列的每个元素的百分比份额,按 ID 分组。
DataFrame 的最终外观应该有这些列:
ID、数字、苹果、橙子、梨子、柠檬
因此,来自 name 列的值正在成为列名。这些列应该具有的值是百分比份额,例如:
编号 123 我有这些数值:2+5+4+7 = 18
所以
apple has: (2+7) / 18 = 0.50
orange has: 5 / 18 = 0.27
pear has: 4 / 18 = 0.23
lemon has: 0
ID apple orange pear lemon
123 0.5 0.27 0.23 0
【问题讨论】: