我有一个数据帧,让数量Fruit在两碗A和B,看起来像这样:
df = pd.DataFrame({'Fruit':['apple','apple','pear','pear','banana','banana'],
'Bowl': ['A','B','A','B','A','B'],
'Value':[15, 20, 332, 240, 344, 211]}); df
Fruit Bowl Value
apple A 15
apple B 20
pear A 332
pear B 240
banana A 311
banana B 211
我有碗中的水果总数“A”和“B”。
num = pd.DataFrame({'Bowl': ['A','B'], 'Num': [330, 200]}); num
Num Type
330 A
200 B
Prop使用num?获得每个碗中每种类型水果的百分比(比例* 100 )的优雅方法是什么?
Fruit Bowl Value Prop
apple A 15 4.55
apple B 20 ...
pear A 332
pear B 240
banana A 45
banana B 27
因此,计算Prop例如(碗A中的苹果数量(15)除以碗A中的水果总数(330)* 100 = 4.55。)
**请注意,水果总数不是碗“A”中苹果+梨+香蕉的总和。你必须使用给出的数字,num因为碗里实际上有更多类型的水果。
解决办法:
实现这一目标的一种方法是首先将num列“合并” 到主df,然后计算比例,如下所示:
# first merge
df_final = pd.merge(df, num, on='Bowl')
# calculate the proportion
df_final['Prop'] = round(df_final.Value / df_final.Num * 100, 2)
# drop the column Num which was not asked in the output
df_final.drop('Num', axis=1, inplace=True)
Fruit Bowl Value Prop
0 apple A 15 3.53
1 pear A 332 78.12
2 banana A 344 80.94
3 apple B 20 6.35
4 pear B 240 76.19
5 banana B 211 66.98








暂无数据