Pandas 数据框列的浮动百分比样式错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54110289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:15:51  来源:igfitidea点击:

Pandas dataframe column of floats to percentage style error

pythonpandasdataframe

提问by Solar

I am trying to convert a pandas dataframe column of floats to percentage style

我正在尝试将浮点数的 Pandas 数据框列转换为百分比样式

C
0.9977
0.1234
1.000
..

to

C
99.77%
12.34%
100%
...

To do this, I am doing:

为此,我正在做:

df['C'] = df['C'].map(lambda n: '{:.2%}'.format(n))

but I am getting the following error:

但我收到以下错误:

ValueError: Unknown format code '%' for object of type 'str'

I also tried '{:,.2%}'with the same error...

我也尝试'{:,.2%}'过同样的错误......

What I am doing wrong?

我做错了什么?

Thanks in advance!!

提前致谢!!

采纳答案by jezrael

First convert column to floats by astype:

首先将列转换为浮点数astype

df['C'] = df['C'].astype(float).map(lambda n: '{:.2%}'.format(n))

Also solution should be simplify:

解决方案也应该简化:

df['C'] = df['C'].astype(float).map("{:.2%}".format)

EDIT:

编辑:

Problem is some non numeric values in column.

问题是列中有一些非数字值。



Replace non numeric to 0:

将非数字替换为0

print (df)
                  C
0            0.9977
1            0.1234
2  Covered fraction
df['C'] = pd.to_numeric(df['C'], errors='coerce').fillna(0).map("{:.2%}".format)
print (df)
        C
0  99.77%
1  12.34%
2   0.00%

Or remove rows with these values:

或删除具有这些值的行:

df['C'] = pd.to_numeric(df['C'], errors='coerce')
df = df.dropna(subset=['C'])
df['C'] = df['C'].astype(float).map("{:.2%}".format)
print (df)
        C
0  99.77%
1  12.34%

回答by Mohit Motwani

You can also use df.style:

您还可以使用df.style

df.style.format({'C': '{:.2%}'})

If your series data type is not an issue and want to use it as string try:

如果您的系列数据类型不是问题并且想将其用作字符串,请尝试:

df['C'] = df.C.apply(lambda x: f"{x[:x.find('.')+3]}%")
df
    C
0   0.99%
1   0.12%
2   1.00%

OR if using python <3.6:

或者,如果使用 python <3.6:

df['C'] = df.C.apply(lambda x: x[:x.find('.')+3]+'%')

Using Jezrael's idea convert to numeric column and invalid strings as 0:

使用 Jezrael 的想法转换为数字列和无效字符串为 0:

df['C'] = pd.to_numeric(df['C'], errors='coerce').fillna(0)
df.style.format({'C': '{:.2%}'})