首页 > 解决方案 > 为什么我的 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

标签: pythonpandastabula

解决方案


由于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

推荐阅读