Home > Blockchain >  How do I edit the string format of several Pandas DataFrame float columns?
How do I edit the string format of several Pandas DataFrame float columns?

Time:10-17

I have a pd.DataFrame of floats:

import numpy as np
import pandas as pd

pd.DataFrame(np.random.rand(5, 5))
          0         1         2         3         4
0  0.795329  0.125540  0.035918  0.645191  0.819097
1  0.755365  0.333681  0.466814  0.892638  0.610947
2  0.545204  0.313946  0.538049  0.237857  0.365573
3  0.026813  0.867013  0.843798  0.923359  0.464778
4  0.514968  0.201144  0.853341  0.951981  0.214948

I'm trying to format all of them as percentage:

         0        1        2        3        4
0 "25.60%" "11.55%" "98.62%" "73.16%" "38.85%"
1 "26.01%" "28.57%" "65.21%" "32.55%" "93.45%"
2 "19.99%" "41.97%" "57.21%" "61.26%" "83.34%"
3 "41.54%" "71.02%" "52.93%" "42.78%" "49.77%"
4 "33.77%" "70.48%" "36.64%" "97.42%" "83.19%"

or

       0      1      2      3      4
0 25.60% 11.55% 98.62% 73.16% 38.85%
1 26.01%  8.57% 65.21% 32.55% 93.45%
2 19.99% 41.97% 57.21% 61.26% 83.34%
3 41.54%  1.02% 52.93% 42.78% 49.77%
4 33.77% 70.48% 36.64% 97.42% 83.19%

Many solutions exist, but for a single column, for example here. I'm trying to edit the values, so I'm not interested in changing the float display format.

How can I proceed?

CodePudding user response:

Try this:

df = df.applymap('{:,.2%}'.format)
  • Related