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

2024-04-25 10:34:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图格式化一个'年'的输出,它被存储为一个浮点数,四舍五入到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

也许我走错了路


Tags: ofmodmostdfcommonminyearmax
1条回答
网友
1楼 · 发布于 2024-04-25 10:34:49

如果Series中的一个值是float类型的(在您的场景中就是这种情况),那么mode函数将输出float值。最好确保系列值都是类型的整数,在事实之前

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

如果你有NaN的存在,试试这个:

df["birth_year"] = df["birth_year"].astype(pd.Int64Dtype())

相关问题 更多 >