Home > Enterprise >  Number of digits after decimal point in pandas
Number of digits after decimal point in pandas

Time:10-19

I have CSV file with data:

Number
1.1
2.2
4.1
5.4
9.176
14.54345774
16.25664

If I print to display with pandas I get:

df = pd.read_csv('data.csv')
print(df)

      Number
0   1.100000
1   2.200000
2   4.100000
3   5.400000
4   9.176000
5  14.543458
6  16.256640

But if I cut 14.54345774 to 14.543 output is changed:

     Number
0   1.10000
1   2.20000
2   4.10000
3   5.40000
4   9.17600
5  14.54300
6  16.25664

The first case number of digits after decimal point in pandas is 6, second case is 5.

Why format is changed? What pandas parameters should I change so these cases are equal? I want the number of digits after the decimal point to be constant and digits after the decimal point is round to max digits after the decimal point if it possibly.

UPDATE:

IMO, This moment arises on data initialization, so round don't get to desirable result if I want use 6 digits. It only can be decrease, (6->5 digits), but it can't be increased (5->6).

CodePudding user response:

You can use pd.set_option to set the decimal number display precision to e.g. 5 in this case:

pd.set_option("display.precision", 5)

or use:

pd.options.display.float_format = '{:.5f}'.format

Result:

print(df)    # with original value of 14.54345774


     Number
0   1.10000
1   2.20000
2   4.10000
3   5.40000
4   9.17600
5  14.54346
6  16.25664

CodePudding user response:

You can use df.round(decimals=val) to fix number of digits after decimal to val.

Also, when you changed to 14.453, pandas didn't needed to show 6 digits then as 16.25664 has most digits after the decimal (i.e. 5) and so now it started showing 5 digits. You can fix this to some constant value so that it doesn't changes with operations.

  • Related