Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...