Home > Mobile >  Turn a float type number into percentage by row on a Data Frame- Python
Turn a float type number into percentage by row on a Data Frame- Python

Time:12-15

Hope you are doing ok. I have the following DataFrame:

Date Income_type Mike Joan
2021/10/31 Salary 25 32
2021/10/31 Investments 10 9
2021/10/31 Investments/Salary 0,4 0,28
2021/09/30 Salary 30 36
2021/09/30 Investments 15 6
2021/09/30 Investments/Salary 0,5 0,16

And I want to turn the Investments /Salary row numbers into a percentage, like this:

Date Income_type Mike Joan
2021/10/31 Salary 25 32
2021/10/31 Investments 10 9
2021/10/31 Investments/Salary 40% 28%
2021/09/30 Salary 30 36
2021/09/30 Investments 15 6
2021/09/30 Investments/Salary 50% 16%

I have tried the following but it hasn't worked:

df['Mike'] = np.where(df['Income_type']=='Investments/salary',df['Mike'].astype(float).map(lambda n: '{:.2%}'.format(n)),df['Mike'])

Any ideas?

CodePudding user response:

Try this :

df.update(
    df.loc[df.Income_type =='Investments/Salary'][['Mike','Jordan']]\
        .replace(to_replace =',', value = '.', regex = True).astype(float)
        )

df.update(df.loc[df.Income_type =='Investments/Salary']['Mike'].map("{:.2%}".format))
df.update(df.loc[df.Income_type =='Investments/Salary']['Jordan'].map("{:.2%}".format))

CodePudding user response:

You can use lambda functions like this. I tested it with synthetic data :

df.Mike = df.Mike.astype(float)

def make_percentage(x):
    if  float(x)<1:
        return str(float(x)*100) '%'
    else: return x
df.Mike = df.Mike.apply(lambda x: make_percentage(x))
  • Related