Sol*_*lar 4 python dataframe pandas
我正在尝试将浮点数的 Pandas 数据框列转换为百分比样式
C
0.9977
0.1234
1.000
..
Run Code Online (Sandbox Code Playgroud)
到
C
99.77%
12.34%
100%
...
Run Code Online (Sandbox Code Playgroud)
为此,我正在做:
df['C'] = df['C'].map(lambda n: '{:.2%}'.format(n))
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
ValueError: Unknown format code '%' for object of type 'str'
Run Code Online (Sandbox Code Playgroud)
我也尝试'{:,.2%}'过同样的错误......
我做错了什么?
jez*_*ael 11
首先将列转换为浮点数astype:
df['C'] = df['C'].astype(float).map(lambda n: '{:.2%}'.format(n))
Run Code Online (Sandbox Code Playgroud)
解决方案也应该简化:
df['C'] = df['C'].astype(float).map("{:.2%}".format)
Run Code Online (Sandbox Code Playgroud)
编辑:
问题是列中有一些非数字值。
将非数字替换为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%
Run Code Online (Sandbox Code Playgroud)
或删除具有这些值的行:
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%
Run Code Online (Sandbox Code Playgroud)
您还可以使用df.style:
df.style.format({'C': '{:.2%}'})
Run Code Online (Sandbox Code Playgroud)
如果您的系列数据类型不是问题并且想将其用作字符串,请尝试:
df['C'] = df.C.apply(lambda x: f"{x[:x.find('.')+3]}%")
df
C
0 0.99%
1 0.12%
2 1.00%
Run Code Online (Sandbox Code Playgroud)
或者如果使用 python <3.6:
df['C'] = df.C.apply(lambda x: x[:x.find('.')+3]+'%')
Run Code Online (Sandbox Code Playgroud)
使用 Jezrael 的想法转换为数字列并将无效字符串转换为 0:
df['C'] = pd.to_numeric(df['C'], errors='coerce').fillna(0)
df.style.format({'C': '{:.2%}'})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16602 次 |
| 最近记录: |