Applying different formats to different columns dataframe

前端 未结 2 332
梦谈多话
梦谈多话 2021-01-15 16:01

I have the following df:

table:

     A             B               C                 D
0  0.000000       0.000000      -0.002520          -0.002520
1  0.20         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 16:29

    If you create a dictionary containing the formats, you can use style.format:

    mapper =  {'A': '{0:.2f}%',
               'B': '{0:.3f}%',
               'C': '{0:.3f}%',
               'D': '{0:.2f}%'}
    
    df.style.format(mapper)
    

    Or using apply (which is column-based by default, axis=0)

    df.apply(lambda x: x.apply(mapper[x.name].format))
    
    
             A        B        C       D
    0    0.00%   0.000%  -0.003%  -0.00%
    1    0.21%   0.016%   0.003%   0.02%
    2   -0.01%  -0.000%   0.000%   0.00%
    

    If you have few different formats and many columns, you could of course generate the mapper dictionary.

提交回复
热议问题