如果包含问号 Python 3,则删除 Dataframe 中的行

Remove row in Dataframe if Contains Question Mark Python 3

我是新手,如有错误请多多包涵。 我正在尝试处理成人人口普查数据集。我发现很难删除数据集中的问号。

Link 到数据集:- https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data

我也尝试了给定 link 中的第一个答案:-

但是我收到一个错误

~/anaconda3/lib/python3.6/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
   1251 
   1252             with np.errstate(all='ignore'):
-> 1253                 res = na_op(values, other)
   1254             if is_scalar(res):
   1255                 raise TypeError('Could not compare {typ} type with Series'

~/anaconda3/lib/python3.6/site-packages/pandas/core/ops.py in na_op(x, y)
   1164                     result = method(y)
   1165                 if result is NotImplemented:
-> 1166                     raise TypeError("invalid type comparison")
   1167             else:
   1168                 result = op(x, y)

TypeError: invalid type comparison

请告诉我如何解决这个问题。我正在使用 Python 3.6

谢谢!!

编辑 1:- 这也称为人口普查收入数据集。

首先转换为字符串,然后按 boolean indexing:

过滤
df = df[(df.astype(str) != '?').all(axis=1)]
#alternative solution
#df = df[~(df.astype(str) == '?').any(axis=1)]
print (df)
   X  Y  Z
1  1  2  3
3  4  4  4

或者比较numpy数组:

df = df[(df.values != '?').all(axis=1)]

详情:

比较所有由 astype 转换的字符串,并将条件更改为 !=:

print (df.astype(str) != '?')
       X      Y      Z
0   True   True  False
1   True   True   True
2  False  False   True
3   True   True   True
4  False   True   True

然后检查每行是否 all True 值:

print ((df.astype(str) != '?').all(axis=1))
0    False
1     True
2    False
3     True
4    False
dtype: bool