How to Convert DataFrame Values Into Percentages

Python

In this snippet we convert the values in the dataframe to the percentage each value represent across the row the row.

First we create a 'total' column for each row and then use pipe and lambda to divide each value in the row by the 'total' column and format as a percentage.

 1|  
 2|  df['total'] = df['col_1'] + df['col_2']
 3|  df = df.pipe(lambda x: x.div(x['total'], axis='index')).applymap('{:.0%}'.format)
Did you find this snippet useful?

Sign up for free to to add this to your code library