Hariom Singh
Hariom Singh

Reputation: 3632

Add percentage column to panda dataframe with percent sign

For the below excel which will be used as panda dataframe

   df['% '] = (df['Code Lines'] / df['Code Lines'].sum())*100

Output comes

Language    # of Files  Blank Lines Comment Lines   Code Lines   % 
C++            15         66         35               354      3.064935065
C/C++ Header    1         3          7                 4       0.034632035
Markdown        6         73         0                142      1.229437229
Python         110        1998      2086              4982     43.13419913
Tcl/Tk          1         14         18               273      2.363636364
YAML            1          0         6                 20      0.173160173
Total          134        2154      2152                5775    50

I am trying to get % column should be of only 2 decimal places with a percent sign

Something like this

Language    # of Files  Blank Lines Comment Lines   Code Lines   % 
C++            15         66         35               354      3.06%
C/C++ Header    1         3          7                 4       0.03%
Markdown        6         73         0                142      1.22%

Upvotes: 5

Views: 8581

Answers (1)

jezrael
jezrael

Reputation: 862791

Use round, convert to strings and add %:

df['%'] = ((df['Code Lines'] / df['Code Lines'].sum())*100).round(2).astype(str) + '%'

Upvotes: 12

Related Questions