如果你知道它只是一个有问题的字符串,最快的方法就是用
pd.to_numeric
,回溯包含索引:
>>> pd.to_numeric(df[2])
Traceback (most recent call last):
File "pandas/_libs/src\inference.pyx", line 1021, in pandas._libs.lib.maybe_convert_numeric
ValueError: Unable to parse string "strin"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 1, in
File "...\lib\site-packages\pandas\core\tools\numeric.py", line 126, in to_numeric
coerce_numeric=coerce_numeric)
File "pandas/_libs/src\inference.pyx", line 1052, in pandas._libs.lib.maybe_convert_numeric
ValueError: Unable to parse string "strin" at position 4
不过,我相信这只会是第一次。所以我们可以强制错误,并找到结果
NaN
:
>>> pd.to_numeric(df[2], errors='coerce').isnull()
0 False
1 False
2 False
3 False
4 True
5 False
Name: 2, dtype: bool
在索引4处发现有问题的字符串这将允许您对DataFrame进行子集,以显示转换失败的所有字符串,只需传递
bool
数组到
df[]
打电话来。
编辑:我意识到我没有涉及在多个列中可以找到字符串的情况。为了避免在列上迭代,可以使用以下代码段获取另一个bool数组:
import functools
df.loc[0, 1] = 'another_string'
df[[0,1,2,3]].apply(functools.partial(pd.to_numeric, errors='coerce')).isnull().any(axis=1)
0 True
1 False
2 False
3 False
4 True
5 False
dtype: bool
传递那个
布尔
数组到
数据框[]
呼叫打印:
Name 0 1 2 3
0 Eric 1 another_string 3 4
4 Sam 17 18 strin 20
如果需要行、列坐标,请使用
np.where
:
results = df[[0,1,2,3]].apply(functools.partial(pd.to_numeric, errors='coerce')).isnull()
np.where(results)
# returns both positions: (array([0, 4], dtype=int64), array([1, 2], dtype=int64))
或者,您可以迭代这些值,尝试转换为数值类型,从异常中获取有问题的字符串并查找它:
import re
r = re.compile("(?<=\')\w+(?=\')")
for row in df[2]:
try:
float(row)
except ValueError as exc:
matches = r.findall(str(exc))
for m in matches:
i = (df[2] == m).index
print(f"Found string '{m}' at index {i}")
# prints:
# Found string 'strin' at index Int64Index([4], dtype='int64')
这看起来太复杂了,但我想试试。
最后,给你一个警告。以下代码不会产生警告:
import pandas as pd
df = pd.DataFrame(np.arange(1,25).reshape(6,4))
Attribute = ['Eric', 'Sarah', 'Steve', 'David', 'Sam', 'Joe']
df.insert(0, 'Name', Attribute)
df.loc[4, 2] = 'strin' # no warning
当你打电话
df[2][4]
你打了两个电话:
__getitem__(2)
后来
__getitem__(4)
,我们称之为
chained indexing
,其中
df.loc[4, 2]
只是一个电话这可能会返回数据帧的视图或副本,具体取决于具体情况,这会导致意外的错误。同时使用一个
.loc
打电话可能会更快。请务必阅读文档以获得更详细的解释。