Python 奇怪的裸体行为

Python 奇怪的裸体行为,python,python-3.x,pandas,numpy,Python,Python 3.x,Pandas,Numpy,我在一个包含330万行的文件上迭代,以检查该列的数据类型,并根据它是否包含整数执行操作 虽然像a55950602、a92300416这样的单元格值对于IssubType作为np.integer很容易被识别为False,但对于ga99266e,它会失败 代码: 作为pd进口熊猫 将numpy作为np导入 导入时间 输入数学 start_time = time.time() lstNumberCounts = [] lstIllFormed = [] dfClicks = pd.read_csv(

我在一个包含330万行的文件上迭代,以检查该列的数据类型,并根据它是否包含整数执行操作

虽然像a55950602、a92300416这样的单元格值对于IssubType作为np.integer很容易被识别为False,但对于ga99266e,它会失败

代码: 作为pd进口熊猫 将numpy作为np导入 导入时间 输入数学

start_time = time.time()
lstNumberCounts = []
lstIllFormed = []

dfClicks = pd.read_csv('Oct3_distinct_Members.csv')
dfClicks['UNIV_MBR_ID'] = dfClicks['UNIV_MBR_ID'].str.split('-').str[0]
dfClicks['UNIV_MBR_ID'] = dfClicks['UNIV_MBR_ID'].apply(pd.to_numeric,errors='ignore')

for item in dfClicks['UNIV_MBR_ID']:
    if (np.issubdtype(item,np.integer)):
        lstNumberCounts.append(math.floor(math.log10(item))+1)
else:
    lstIllFormed.append(item)


print("---Processing Time: %s seconds ---" % (time.time() - start_time))
对于上述值,代码运行良好,但其中一个在控制台上抛出错误,如下所示:
TypeError:数据类型“ga99266e”不可理解

pd.\u numeric,errors='ignore'
。因此,对于“ga99266e”,它返回“ga99266e”,这是一个字符串。如果您输入numpys issubd,请键入字符串。(例如,np.issubdtype('int',int)返回True)

因此,您需要首先检查字段是否仍然是字符串,如果不是,则可以检查它是否是numpy整数

尝试:


“a123456”或任何以“a”开头的字符串都适用于
np.issubdtype
,因为numpy将其解释为一个代码,告诉它下面的数字是什么类型的数字

阵列协议类型字符串(请参见阵列接口)

第一个字符指定数据类型,其余字符指定每个项目的字节数,Unicode除外,Unicode将其解释为字符数。项目大小必须对应于现有类型,否则将引发错误。支持的种类有

“?”布尔值

“b”(有符号)字节

“B”无符号字节

“i”(有符号)整数

“u”无符号整数

“f”浮点

“c”复数浮点

“m”时间增量

“M”日期时间

“O”(Python)对象

'S','a'以零结尾的字节(不推荐)

“U”Unicode字符串

“V”原始数据(无效)


这应该有助于alreadySorry,但我应该在该链接中寻找什么呢。我是python的自学者,最近开始使用它来自动执行Errors='ignore'使pd为数值。要返回数值(然后测试issubdtype(…,integer))或输入。如果无法转换为数字,则输入为“ga99266e”。我不知道那是什么类型,但显然np.issubdtype两者都不知道。您可以使用“强制”而不是“忽略”,然后测试它是否为NaN(如果不需要其他字段),或者您需要执行一些不同的解析。明白。但它正确地处理了“a55950602”,这是代码中其他部分的字符串。我很好奇“ga99266e”有什么特别的地方。我已经在我的答案中添加了这一点。真是有趣的行为。
import pandas as pd 
import numpy as np 
import time 
import math
start_time = time.time()
lstNumberCounts = []
lstIllFormed = []

dfClicks = pd.read_csv('Oct3_distinct_Members.csv')
dfClicks['UNIV_MBR_ID'] = dfClicks['UNIV_MBR_ID'].str.split('-').str[0]
dfClicks['UNIV_MBR_ID'] = dfClicks['UNIV_MBR_ID'].apply(pd.to_numeric,errors='ignore')

for item in dfClicks['UNIV_MBR_ID']:
    if not (isinstance(item,str)):
        if (np.issubdtype(item,np.integer)):
            lstNumberCounts.append(math.floor(math.log10(item))+1)
    else:
        lstIllFormed.append(item)


print("---Processing Time: %s seconds ---" % (time.time() - start_time))