Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying different formats to different columns dataframe

Tags:

pandas

I have the following df:

table:

     A             B               C                 D
0  0.000000       0.000000      -0.002520          -0.002520
1  0.209772       0.016262       0.003411           0.024343
2 -0.006474      -0.000152       0.000152           0.000000

The real df has about 12 columns and 40 rows.

I would like to change its format:

The problem I am facing is how can I apply a format to some columns and a different format to other columns . Normally I use to apply formats to entire dfs but not to columns individually.

The desired output would be something like this:

table:

    A             B            C               D
0  0.00%       0.000%      -0.000%          -0.00%
1  0.20%       0.067%       0.001%           0.43%
2 -0.00%      -0.000%       0.015%           0.00%

As you can see in the desired output columns A and D are rounded to 2 signif figures and B and C are rounded to 3 signif figures and added the % to all of them

this is what I have tried and did not work:

 format_AD = "{0:.2f}%".format
 format_BC=  "{0:.3f}%".format

 format_changeAD=[table.loc[:,['A','D']]]
 format_changeBC=[table.loc[:,['B','C']]]

 format_changeAD.apply(format_AD)
 format_changeBC.apply(format_BC)

 return table
like image 798
JamesHudson81 Avatar asked Dec 07 '25 17:12

JamesHudson81


1 Answers

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.

like image 126
Rutger Kassies Avatar answered Dec 09 '25 16:12

Rutger Kassies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!