Search code examples
pandasformat-string

Pandas applymap function does not format numbers


I am running this inside the code lab, to format string to 2 decimal points. However, it does not work. What is wrong please? I am in Colab.

When I issue the following:

format = lambda x: '%.2f' % x
frame.applymap(format)  # applies to every single entry

I get

            b          d            e
Utah    0.950857    -0.472254   -0.109456
Ohio    -0.738897   0.218620    -0.982334
Texas   0.400049    0.412557    -0.262711
Oregon  1.130821    0.236745    1.921072

However, when I issue

frame['e'].map(format)

It returns correct result.

Utah       0.27
Ohio       1.61
Texas      0.26
Oregon    -0.74
Name: e, dtype: object

Here is the my execution. link


Solution

  • Are they strings as you've indicated? If not, you can always use frame.round(2) on a pandas df.

    If it is a string, you could try first converting the column to float and then applying the round function.

    for col in frame.columns:
        frame[col] = frame[col].astype(float)
    frame = frame.round(2)