首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么pandas中的dataframe列不能从float转换为int?

为什么pandas中的dataframe列不能从float转换为int?
EN

Stack Overflow用户
提问于 2021-05-30 12:01:29
回答 1查看 52关注 0票数 1

我正在尝试将一个列从float转换为int。当我执行脚本时,我没有收到错误;但是,浮动数据类型仍然存在。我做错了什么?

数据集以pdf格式读入,并使用tabula转换为csv。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2021-05-30 13:26:48

Pandas 0.24.0开始,您就有了一个solution来将float转换为integer并保留空值。

使用数据类型pd.Int64Dtype (或"Int64")。

代码语言:javascript
复制
>>> 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
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67757569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档