首页 > 解决方案 > Pandas:我可以在列的模式上使用 round() 方法吗?

问题描述

我正在尝试格式化存储为浮点数的“年份”的输出,四舍五入到小数点后 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

也许我正在以错误的方式解决这个问题。

标签: pythonpandasdataframeformat

解决方案


如果 中的单个值Series是浮点类型(在您的场景中出现这种情况),则该mode函数将输出浮点值。最好在事前确保 Series 值都是整数类型。

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

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

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

推荐阅读