[英]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 ![]() |
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:我想将 Investments /Salary 行数转换为百分比,如下所示:
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?有任何想法吗?
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.