Is it possible to replace percentages with a phrase in a column?

Question:

I have a table that I am turning into a graph, so I am making it so that the percentages are just whole numbers. For example: 63.9 would be 64%. I have some percentages that are less than 1%, and I would prefer to not have them read 0%, and rather write, "less than 1%" or something like that. Is this possible? Below I wrote a line of code I tried, which runs, but I received a SettingWithCopyWarning, so there are no reflected changes.

national_df.loc[national_df['percent']==0.152416, 'percent']='less than 1%'
Asked By: Deeda

||

Answers:

You can use pandas.apply and round. If round() == 0 insert 'less than 1%'.

import pandas as pd

# example df
df = pd.DataFrame({'percent' : [0.152416, 1.152416, 10.152416, 63.9]})

# python < 3.8
df['percent'] = df['percent'].apply(lambda x: 'less than 1%' if round(x) == 0 else f'{round(x)}%')

# python >= 3.8
# df['percent'] = df['percent'].apply(lambda x: 'less than 1%' if (res:=round(x)) == 0 else f'{res}%')
print(df)

        percent
0  less than 1%
1            1%
2           10%
3           64%
Answered By: I'mahdi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.