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
1.2k views
in Technique[技术] by (71.8m points)

python - The right way to round pandas.DataFrame?

I want round pandas.DataFrame.

Here is what i have tried so far:

import pandas as pd
data = pd.DataFrame([1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0])
print(round(data))

But when i run this code, i get the following error:

Traceback (most recent call last):
  File "C:Users*****Documents***************.py", line 3, in <module>
    print(round(data))
TypeError: type DataFrame doesn't define __round__ method

What is the right way to round pandas.DataFrame ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

first, you may want to change the definition of your data frame, something like:

data = pd.DataFrame([[1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0]]).T

which results this:

     0    1
0  1.4  6.2
1  2.5  7.6
2  3.8  8.8
3  4.4  9.1
4  5.6  0.0

or:

data = pd.DataFrame({'A':[1.4,2.5,3.8,4.4,5.6],'B':[6.2,7.6,8.8,9.1,0]})

so that you get two columns, otherwise the other list is picked up as index; then:

data.apply(pd.Series.round)

or

import numpy as np
data.apply(np.round)

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

1.4m articles

1.4m replys

5 comments

57.0k users

...