简体   繁体   中英

how to calculate percentage for each cell and replace tha value with result(%) using pandas dataframe?

here is the sample example:

input:
sub del wait 
12  55  11   
13  33  71   

ex: 1st row: del=55*100/12=458.33 wait=11*100/12=91.66

2nd row: del=33*100/13=253.3 wait=71*100/13=546.01

final output should be:

sub del    wait     
12  458.33  91.66   
13  253.3   546.01  

Select both columns, multiple by 100 and divide by DataFrame.div , then assign columns back with DataFrame.round if necessary:

df[['del','wait']] = df[['del','wait']].mul(100).div(df['sub'], axis=0).round(2)
print (df)
   sub     del    wait
0   12  458.33   91.67
1   13  253.85  546.15

Or divide by numpy array created by Series.to_numpy with shape (N x 1) for divide per rows:

df[['del','wait']] = (df[['del','wait']] * 100 / df['sub'].to_numpy()[:, None]).round(2)
print (df)
   sub         del        wait
0   12  458.333333   91.666667
1   13  253.846154  546.153846

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