Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe column of floats to percentage style error

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?

like image 724
Solar Avatar asked Dec 04 '22 19:12

Solar


1 Answers

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%
like image 63
jezrael Avatar answered Dec 29 '22 00:12

jezrael