python - 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
也许我正在以错误的方式解决这个问题。
解决方案
如果 中的单个值Series
是浮点类型(在您的场景中出现这种情况),则该mode
函数将输出浮点值。最好在事前确保 Series 值都是整数类型。
df["birth_year"] = df["birth_year"].astype(int)
如果你有NaN
's 的存在,试试这个:
df["birth_year"] = df["birth_year"].astype(pd.Int64Dtype())
推荐阅读
- xpages - 两个 DynamicView 链接
- android - RecyclerView 内容出现在 BottomNavBar 后面
- php - 在 php 中设置 mysql 属性会更改每个人的属性还是仅更改当前连接?
- azure-devops - VSTS 显示一个空的仓库
- html - divs的flexbox CSS排列
- java - 无法导入spring配置类
- mysql - 如何分组此 SQL
- extjs - Ext JS表格布局如何强制仅右侧的最后一个元素
- tensorflow - 如何将基于 scikit-kearn 的损失添加到神经网络?
- javascript - 如何有条件地在 vue.js 中添加属性?