简体   繁体   English

在数据框上按行将浮点类型数转换为百分比 - Python

[英]Turn a float type number into percentage by row on a Data Frame- Python

Hope you are doing ok.希望你一切都好。 I have the following DataFrame:我有以下 DataFrame:

Date日期 Income_type收入类型 Mike麦克风 Joan
2021/10/31 2021/10/31 Salary薪水 25 25 32 32
2021/10/31 2021/10/31 Investments投资 10 10 9 9
2021/10/31 2021/10/31 Investments/Salary投资/薪水 0,4 0,4 0,28 0,28
2021/09/30 2021/09/30 Salary薪水 30 30 36 36
2021/09/30 2021/09/30 Investments投资 15 15 6 6
2021/09/30 2021/09/30 Investments/Salary投资/薪水 0,5 0,5 0,16 0,16

And I want to turn the Investments /Salary row numbers into a percentage, like this:我想将 Investments /Salary 行数转换为百分比,如下所示:

Date日期 Income_type收入类型 Mike麦克风 Joan
2021/10/31 2021/10/31 Salary薪水 25 25 32 32
2021/10/31 2021/10/31 Investments投资 10 10 9 9
2021/10/31 2021/10/31 Investments/Salary投资/薪水 40% 40% 28% 28%
2021/09/30 2021/09/30 Salary薪水 30 30 36 36
2021/09/30 2021/09/30 Investments投资 15 15 6 6
2021/09/30 2021/09/30 Investments/Salary投资/薪水 50% 50% 16% 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?有任何想法吗?

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))

You can use lambda functions like this.您可以像这样使用 lambda 函数。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM