如何找出 pandas DF 列中哪些值无法使用 astype 函数转换为“int”类型

Ber*_*nes 5 types pandas

我正在使用数据框,我必须将列转换为 int 类型

我使用以下符号:

result_df['ftmSectionId'] = result_df['ftmSectionId'].astype('int') 
Run Code Online (Sandbox Code Playgroud)

DF 有几百万行,因此显然有一些值无法转换为 int (可能包括逗号或句点...)我收到错误:

ValueError: invalid literal for int() with base 10: 'not'
Run Code Online (Sandbox Code Playgroud)

现在根据这个问题: How do I fix invalidliteral for int() with base 10 error in pandas

我可以使用:

data.Population1 = pd.to_numeric(data.Population1, errors="coerce")
Run Code Online (Sandbox Code Playgroud)

这有效。

但这样我就不知道为什么我一开始就出错了。由于我正在使用的数据库的性质,我希望该特定列仅包含整数。如何查询该列以找出哪些值无法使用简单方法 .astype('int') 转换为 'int' ?

谢谢

其他可能的答案,但不重复: Unable to conversion pandas dataframe column to int variable type using .astype(int) method 这个问题解决了同样的问题,只是他们知道问题是该列包含 NaN 并且将其删除。我不知道这里有什么问题,我的目标不仅仅是转换为“int”,而是捕获问题值

Mus*_*dın 5

您仍然可以使用并获取原始系列中的errors="coerce"值:NaN

s = pd.Series(["apple", "1.0", "2", -3, "pear", "12,84"])

nans = pd.to_numeric(s, errors="coerce").isna()
Run Code Online (Sandbox Code Playgroud)

然后布尔索引给出:

>>> s[nans]

0    apple
4     pear
5    12,84
dtype: object
Run Code Online (Sandbox Code Playgroud)


Moh*_*sha 2

这是一个额外的替代方案:

def check_float(value):
try:
    float(value)
    return np.NaN
except ValueError:
    return value
Run Code Online (Sandbox Code Playgroud)

我们可以调用该函数:在此处输入链接描述

test = pd.Series([42, 3.1415, 'banana'])
test.apply(check_float)

0       NaN
1       NaN
2    banana
dtype: object
Run Code Online (Sandbox Code Playgroud)

但我不确定它是否可扩展。

这是讨论此问题的帖子在数字列中查找无效值