stefanodv
stefanodv

Reputation: 533

Formatting numeric columns of a pandas data frame with a specified number of decimal digits

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

Upvotes: 2

Views: 8766

Answers (2)

Josh Friedlander
Josh Friedlander

Reputation: 11657

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

Upvotes: 0

BENY
BENY

Reputation: 323306

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

Upvotes: 1

Related Questions