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?
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%
df['rating'] = df['rating'].mul(100).astype(int).astype(str).add('%')
print(df)
Output:
name rating
0 Johnny 100%
1 Brad 90%
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