Calculate percentage on DataFrame

喜欢而已 提交于 2021-02-11 06:07:27

问题


I'm trying to calculate the percentage of each crime of the following Dataframe:

        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

So I should calculate first the total of crimes per year and then use that to calculate the percentage of each crime. I was trying the following:

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

Any thoughts? Thank you!


回答1:


Use function DataFrame.div for divide by 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


来源:https://stackoverflow.com/questions/50831217/calculate-percentage-on-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!