I am trying to convert a pandas dataframe column of floats to percentage style
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...
What I am doing wrong?
First convert column to floats by 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
:
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%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With