Home > Back-end >  Divide almost similar columns and get percentage
Divide almost similar columns and get percentage

Time:09-17

I have a dataframe df

x y z x_o y_o z_o
1 5 3 10  20  15
3 2 7 10  15  20

How can I divide x,y,z with their respective _o part and get percentage?

desired output:

x y z x%  y%     z%
1 5 3 10  25     20
3 2 7 30  13.33  35
 

CodePudding user response:

You can select all columns by lists, divide DataFrames with multiple 100 and append to original DataFrame:

df = (df.join(df[['x','y','z']].div(df[['x_o','y_o','z_o']].to_numpy())
             .mul(100)
             .round(2)
             .add_suffix('%')))
print (df)
   x  y  z  x_o  y_o  z_o    x%     y%    z%
0  1  5  3   10   20   15  10.0  25.00  20.0
1  3  2  7   10   15   20  30.0  13.33  35.0

cols = ['x','y','z']
df = (df.join(df[cols].div(df[[f'{c}_o' for c in cols]].to_numpy())
             .mul(100)
             .round(2)
             .add_suffix('%')))
print (df)
   x  y  z  x_o  y_o  z_o    x%     y%    z%
0  1  5  3   10   20   15  10.0  25.00  20.0
1  3  2  7   10   15   20  30.0  13.33  35.0

Loop solution:

for c in ['x','y','z']:
    df[f'{c}%'] = df[c].div(df[f'{c}_o']).mul(100).round(2)

CodePudding user response:

You may try:

cols = ['x','y','z']
df2 = df[pd.Series(cols).map('{}_o'.format)]
df2.columns = cols
df[pd.Series(cols).map('{}%'.format)] = df[cols].mul(100).div(df2)

print(df):

   x  y  z  x_o  y_o  z_o    x%         y%    z%
0  1  5  3   10   20   15  10.0  25.000000  20.0
1  3  2  7   10   15   20  30.0  13.333333  35.0
  • Related