python - 为什么我的 pandas 中的数据框列不会从浮点数转换为整数?
问题描述
我正在尝试将列从 float 转换为 int。当我执行脚本时,我没有收到错误;但是, float dtype 仍然存在。我究竟做错了什么?
数据集以 pdf 格式读入,并使用表格转换为 csv。
apd_log = pd.read_csv('/home/d/my_datasets/police_log.csv')
apd_log = apd_log.astype({'Incident #': int}, errors='ignore')
apd_log.dtypes
Incident # float64
Date object
Time object
Address object
Incident Type object
Action Taken object
dtype: object
解决方案
由于Pandas 0.24.0
,您有一个解决方案float
来转换 integer
并保持空值。
使用 dtype pd.Int64Dtype
(或"Int64"
)。
>>> df['Incident #']
0 9.0
1 1.0
2 NaN
3 2.0
4 3.0
Name: Incident #, dtype: float64
>>> df['Incident #'].astype(int) # raise an exception without errors='ignore'
...
ValueError: Cannot convert non-finite values (NA or inf) to integer
>>> df['Incident #'].astype("Int64")
0 9
1 1
2 <NA>
3 2
4 3
Name: Incident #, dtype: Int64
推荐阅读
- string - Oracle 12c:在 SQLdeveloper 中尝试使用时,listagg 函数无法识别“on overflow”子句
- amazon-web-services - 第二个事件使第一个事件完成
- powershell - 通过 Powershell 卸载程序
- sql - 如何为以下结果表编写此表的查询
- json - 需要帮助通过正确附加 url 请求来更新 react .map 列表中的数据库数据
- firebase - Flutter Firebase 数据库变量在方法后未收到值
- c++ - (N, vector< int >(M, -1)) 有什么相似之处?
- django - 如何通过forloop用两张不同的卡片打印数据?
- ffmpeg - 使用 ffmpeg 在电影前添加 JPG 图像
- visual-studio-code - Deno Lint - 禁用/添加规则到 linter