简体   繁体   English

如何在 python 中的 dataframe 中将列平均值舍入为 integer

[英]How to round the column mean to integer in a dataframe in python

I am trying to round off the mean value of the column "Age" to integer with the following code,我正在尝试使用以下代码将“年龄”列的平均值四舍五入为 integer,

df['Age'].mean().round()

but I get this error,但我得到这个错误,

'float' object has no attribute 'round'. 'float' object 没有属性 'round'。

Something like this:像这样的东西:

df['Age'].mean().round(0).astype(int)

Because scalar is returned from df['Age'].mean() , use round method:因为标量是从df['Age'].mean()返回的,所以使用round方法:

df = pd.DataFrame({'Age':[10, 20, 34]})

print (df['Age'].mean())
21.333333333333332

print (round(df['Age'].mean()))
21

print (round(df['Age'].mean(), 3))
21.333

I found this to work nicely.我发现这很好用。 Should bypass the error and give expected output all in one line of code:应该绕过错误并在一行代码中给出预期的 output :

int(round(df['column'].mean(),0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM