I have a dataframe df
I want to calculate the percentage based on the column total
.
Suppose I have:
df = pd.DataFrame({
'ID': range(1, 4),
'col1': [10, 5, 10],
'col2': [15, 10, 15],
'col3': [10, 15, 15],
'total': [35, 30, 40]
})
print(df)
ID col1 col2 col3 total
0 1 10 15 10 35
1 2 5 10 15 30
2 3 10 15 15 40
I want to get:
ID col1 col2 col3 total
0 1 28.57 % 42.85 % 28.57 % 100 %
1 2 16.66 % 33.33 % 50 % 100 %
2 3 25 % 37.5% 37.5 % 100 %
Use
>>> df.iloc[:, 1:] = df.iloc[:, 1:].div(df['total'], axis=0).mul(100).round(2).astype(str).add(' %')
>>> df
ID col1 col2 col3 total
0 1 28.57 % 42.86 % 28.57 % 100.0 %
1 2 16.67 % 33.33 % 50.0 % 100.0 %
2 3 25.0 % 37.5 % 37.5 % 100.0 %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With