我正在尝试将一个列从float转换为int。当我执行脚本时,我没有收到错误;但是,浮动数据类型仍然存在。我做错了什么?
数据集以pdf格式读入,并使用tabula转换为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发布于 2021-05-30 13:26:48
从Pandas 0.24.0开始,您就有了一个solution来将float转换为integer并保留空值。
使用数据类型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: Int64https://stackoverflow.com/questions/67757569
复制相似问题