简体   繁体   中英

how to calculate percentage for particular rows for given columns using python pandas?

student,total,m1,m2,m3
a,500,120,220,160
b,600,180,120,200

This is my dataframe and I just want to calculate m1,m2,m3 columns as percentages of the total column. I need output like following dataframe

student,total,m1,m2,m3,m1(%),m2(%),m3(%)
a,500,120,220,160,24,44,32
...

for example m1(%) column will be calculated by using (m1/total)*100 .

I think you can use div :

df = pd.DataFrame({'total': {0: 500, 1: 600}, 
                   'm1': {0: 120, 1: 180}, 
                   'm3': {0: 160, 1: 200}, 
                   'student': {0: 'a', 1: 'b'},
                   'm2': {0: 220, 1: 120}},
                    columns=['student','total','m1','m2','m3'])

print df
  student  total   m1   m2   m3
0       a    500  120  220  160
1       b    600  180  120  200


df[['m1(%)','m2(%)','m3(%)']] = df[['m1','m2','m3']].div(df.total, axis=0)*100
print df
  student  total   m1   m2   m3  m1(%)  m2(%)      m3(%)
0       a    500  120  220  160   24.0   44.0  32.000000
1       b    600  180  120  200   30.0   20.0  33.333333

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM