为什么即使调用了str.strip,数值也被视为非数字?
这就是我的处境:
df['ID'] = df['ID'].str.strip()
id = df['ID']
indices = [ i for (i, v) in enumerate(id.str.isnumeric()) if v == False ]
non_numeric = id.filter(indices)
id.head(-5)
And this is the output of id.head(-5):
141 C536379
154 C536383
235 C536391
236 C536391
237 C536391
...
470612 576618
470614 576618
470616 576618
470618 576618
470673 576618
Name: ID, Length: 7892, dtype: object
为什么所有不以字母开头的数字仍在非数字数组中
一开始我以为是因为前面的空白,但后来我添加了strip((,一切都没有改变。
编辑:我需要分析系列中的非数值,所以我正在尝试提取它们。
看看你最近的编辑,我相信这就是你想要做的:
"编辑:我需要分析系列中的非数值,所以我正在尝试提取它们">
只看字符串有很多方法。这是一个。使用pd.to_numeric()
创建一个系列s
并传递errors='coerce'
。这将返回非数字数据的NaN
值。从那里,使用isnull()
:将其作为过滤器传递到该系列的NaN
行的数据帧
s = pd.to_numeric(df['ID'], errors='coerce')
df = df[s.isnull()]
df
ID
141 C536379
154 C536383
235 C536391
236 C536391
237 C536391