计算DataFrame上的百分比

2022-02-26 00:00:00 python pandas dataframe pandas-groupby

问题描述

我正在尝试计算以下数据帧的每个犯罪的百分比:

        Violent     Murder      Larceny_Theft   Vehicle_Theft
Year
1960    288460      3095700     1855400         328200
1961    289390      3198600     1913000         336000
1962    301510      3450700     2089600         366800
1963    316970      3792500     2297800         408300
1964    364220      4200400     2514400         472800
所以我应该先计算每年的犯罪总数,然后用它来计算每种犯罪的百分比。我正在尝试以下操作:

> perc = (crime *100) / crime.sum(axis=1)

有什么想法吗? 谢谢!


解决方案

使用函数DataFrame.divFOR除以Series

perc = crime.mul(100).div(crime.sum(axis=1), axis=0)
#perc = (crime *100).div(crime.sum(axis=1), axis=0)
print (perc)
       Violent     Murder  Larceny_Theft  Vehicle_Theft
Year                                                   
1960  5.180899  55.600457      33.323994       5.894651
1961  5.044283  55.753976      33.345012       5.856730
1962  4.856320  55.579268      33.656487       5.907925
1963  4.650675  55.644649      33.713981       5.990695
1964  4.822943  55.621029      33.295285       6.260742

相关文章