2

I have to format a column of numbers in a data frame pandas rounding for two but with three decimal digits where the last is 0 and the column does not have to be a string. The numbers of this column must be represented so once exported to Excel.

d = {'col1': [0.567, 2.54765476], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

         col1  col2
0       0.567     3
1  2.54765476     4

expected:

    col1  col2
0  0.560     3
1  2.540     4

It is important that the type remain numerical

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
stefanodv
  • 463
  • 3
  • 11
  • 20

2 Answers2

1

You may need floor div then format

df.col1=(np.floor(df.col1*100)/100).map('{:,.3f}'.format)
df
Out[355]: 
    col1  col2
0  0.560     3
1  2.540     4
BENY
  • 317,841
  • 20
  • 164
  • 234
0

If, as you say, you need rounding rather than string truncation, then assuming your second value should be 2.550, you can use Pandas float display options, as linked to here by @G. Anderson:

pd.options.display.float_format = '{:,.3f}'.format
df.col1 = df.col1.round(2)
df
>   
    col1    col2
0   0.570   3
1   2.550   4
Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75