熊猫将字符串转换为int
我有一个具有ID号的大数据框架:
ID.head()
Out[64]:
0 4806105017087
1 4806105017087
2 4806105017087
3 4901295030089
4 4901295030089
目前这些都是字符串。
我想在不使用循环的情况下转换为int
- 为此,我使用id.astype(int)
。
问题在于我的某些行包含肮脏的数据,这些数据不能转换为int
,例如
ID[154382]
Out[58]: 'CN414149'
我如何(不使用循环)删除这些类型的出现,以便我可以使用astype < /代码>放心?
I have a large dataframe with ID numbers:
ID.head()
Out[64]:
0 4806105017087
1 4806105017087
2 4806105017087
3 4901295030089
4 4901295030089
These are all strings at the moment.
I want to convert to int
without using loops - for this I use ID.astype(int)
.
The problem is that some of my lines contain dirty data which cannot be converted to int
, for e.g.
ID[154382]
Out[58]: 'CN414149'
How can I (without using loops) remove these type of occurrences so that I can use astype
with peace of mind?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将参数
errors='coerce'
添加到函数to_numeric
:如果
ID
是column:但非数字会转换为
NaN
,所以所有值都是浮动
。对于
int
需要将NaN
转换为某个值,例如0
然后转换为int
:示例:
编辑:如果使用pandas 0.25+ 则可以使用
integer_na
:You need add parameter
errors='coerce'
to functionto_numeric
:If
ID
is column:but non numeric are converted to
NaN
, so all values arefloat
.For
int
need convertNaN
to some value e.g.0
and then cast toint
:Sample:
EDIT: If use pandas 0.25+ then is possible use
integer_na
:.astype('int64')
来表示 64 位有符号整数:如果您不想丢失其中包含字母的值,请使用
str .replace()
使用正则表达式模式来删除非数字字符。然后输入
转换成
use
.astype('int64')
for 64-bit signed integers:If you don't want to lose the values with letters in them, use
str.replace()
with a regex pattern to remove the non-digit characters.Then input
converts into
我通过这样做在最新版本的 jupyter 笔记本中于 2024 年 1 月解决了这个问题。
始终使用 try 和 catch 来查看它是否不起作用,而不是出现错误。
我检查了“Price”数据类型,之前它是“o”,现在显示“int(64)”。这就是我们都在寻找的。
I solved it Jan-2024 in the latest version of jupyter notebook by doing this.
Always use try and catch to see if its not working than what the error.
I checked the "Price" data type and previously it was "o" and now its showing "int(64)". That's what we all looking for.