熊猫将字符串转换为int

发布于 2025-01-21 03:40:18 字数 449 浏览 3 评论 0原文

我有一个具有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只怪假的太真实 2025-01-28 03:40:18

您需要将参数 errors='coerce' 添加到函数 to_numeric

ID = pd.to_numeric(ID, errors='coerce')

如果ID是column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

但非数字会转换为NaN,所以所有值都是浮动

对于 int 需要将 NaN 转换为某个值,例如 0 然后转换为 int

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

示例:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

编辑:如果使用pandas 0.25+ 则可以使用 integer_na

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN
往昔成烟 2025-01-28 03:40:18
  1. 如果您在这里是因为使用
OverflowError: Python int too large to convert to C long

.astype('int64') 来表示 64 位有符号整数:

df['ID'] = df['ID'].astype('int64')

如果您不想丢失其中包含字母的值,请使用 str .replace() 使用正则表达式模式来删除非数字字符。

df['ID'] = df['ID'].str.replace('[^0-9]', '', regex=True).astype('int64')

然后输入

0    4806105017087
1    4806105017087
2         CN414149
Name: ID, dtype: object

转换成

0    4806105017087
1    4806105017087
2           414149
Name: ID, dtype: int64
  1. If you're here because you got
OverflowError: Python int too large to convert to C long

use .astype('int64') for 64-bit signed integers:

df['ID'] = df['ID'].astype('int64')

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.

df['ID'] = df['ID'].str.replace('[^0-9]', '', regex=True).astype('int64')

Then input

0    4806105017087
1    4806105017087
2         CN414149
Name: ID, dtype: object

converts into

0    4806105017087
1    4806105017087
2           414149
Name: ID, dtype: int64
微暖i 2025-01-28 03:40:18

我通过这样做在最新版本的 jupyter 笔记本中于 2024 年 1 月解决了这个问题。

始终使用 try 和 catch 来查看它是否不起作用,而不是出现错误。
我检查了“Price”数据类型,之前它是“o”,现在显示“int(64)”。这就是我们都在寻找的。

try:
    car_sales["Price"] = car_sales["Price"].str.replace('[\$\,]|\.\d*', '', regex=True).astype(int)
except ValueError as e:
    print(f"Error: {e}") 

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.

try:
    car_sales["Price"] = car_sales["Price"].str.replace('[\$\,]|\.\d*', '', regex=True).astype(int)
except ValueError as e:
    print(f"Error: {e}") 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文