Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Pandas dataframe values to percentage

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 %
like image 745
prashant Avatar asked Dec 13 '22 07:12

prashant


1 Answers

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 %
like image 58
timgeb Avatar answered Dec 29 '22 08:12

timgeb