Pandas dataframe column of floats to percentage style error

Viewed 24286

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?

2 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%

You can also use 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:

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

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

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