熊猫:我可以在列模式下使用round()方法吗?

我试图格式化存储为浮点数的“ year”的输出格式,四舍五入到小数点后0位,并删除数据框信息。

# Display earliest,most recent,and most common year of birth
print('Earliest year of birth:')
min_yob = df.birth_year.min()
print(round(min_yob))

print('Max year of birth: ')
max_yob = df.birth_year.max()
print(round(max_yob))

print('Most common year of birth: ')
mod_yob = df.birth_year.mode()
print(round(mod_yob))

我为此获得的输出如下:

Earliest year of birth:
1899
Max year of birth: 
2016
Most common year of birth: 
0    1989.0
dtype: float64

如果我将mod_yob转换为int,它将正确显示,但是我不确定为什么round()在这里不起作用。

 Most common year of birth: 
 1989

也许我会以错误的方式进行操作。

zhaofc 回答:熊猫:我可以在列模式下使用round()方法吗?

如果Series中的单个值是float类型(在您的情况下就是这种情况),则mode函数将输出float值。最好确保Series值在事实发生之前都是 类型。

df["birth_year"] = df["birth_year"].astype(int)

如果有NaN,请尝试以下操作:

df["birth_year"] = df["birth_year"].astype(pd.Int64Dtype())
本文链接:https://www.f2er.com/3169111.html

大家都在问