Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format decimals as percentages in a column

Let's say I have the following pandas DataFrame:

df = pd.DataFrame({'name': ['Johnny', 'Brad'], 'rating': [1.0, 0.9]})

I want to convert the rating column from a decimal to a percentage as a string (e.g. 1.0 to '100%'). The following works okay:

def decimal_to_percent_string(row):
    return '{}%'.format(row['rating'] * 100)

df['rating'] = df.apply(func=decimal_to_percent_string, axis=1)

This seems very inefficient to me as it applies the function to the entire DataFrame which isn't ideal because my DataFrame is very large. Is there a better way to do this?

like image 805
Johnny Metz Avatar asked Sep 20 '25 15:09

Johnny Metz


2 Answers

Use pandas' broadcasting operations:

df.rating = (df.rating * 100).astype(str) + '%'
df 
     name  rating
0  Johnny  100.0%
1    Brad   90.0%

Alternatively, using df.mul and df.add:

df.rating = df.rating.mul(100).astype(str).add('%')
df
     name  rating
0  Johnny  100.0%
1    Brad   90.0%
like image 87
cs95 Avatar answered Sep 22 '25 06:09

cs95


df['rating'] = df['rating'].mul(100).astype(int).astype(str).add('%')
print(df)

Output:

     name rating
0  Johnny   100%
1    Brad    90%
like image 40
Scott Boston Avatar answered Sep 22 '25 04:09

Scott Boston