Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round pandas column with precision but no trailing 0

Not duplicate because I'm asking about pandas round().

I have a dataframe with some columns with numbers. I run

df = df.round(decimals=6)

That successfully truncated the long decimals instead of 15.36785699998 correctly writing: 15.367857, but I still get 1.0 or 16754.0 with a trailing zero.

How do I get rid of the trailing zeros in all the columns, once I ran pandas df.round() ?

I want to save the dataframe as a csv, and need the data to show the way I wish.

like image 368
pashute Avatar asked Oct 29 '25 00:10

pashute


1 Answers

df = df.round(decimals=6).astype(object)

Converting to object will allow mixed representations. But, keep in mind that this is not very useful from a performance standpoint.


df

           A          B
0   0.149724  -0.770352
1   0.606370  -1.194557
2  10.000000  10.000000
3  10.000000  10.000000
4   0.843729  -1.571638
5  -0.427478  -2.028506
6  -0.583209   1.114279
7  -0.437896   0.929367
8  -1.025460   1.156107
9   0.535074   1.085753

df.round(6).astype(object)

          A         B
0  0.149724 -0.770352
1   0.60637  -1.19456
2        10        10
3        10        10
4  0.843729  -1.57164
5 -0.427478  -2.02851
6 -0.583209   1.11428
7 -0.437896  0.929367
8  -1.02546   1.15611
9  0.535074   1.08575
like image 50
cs95 Avatar answered Oct 30 '25 15:10

cs95