gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:13 24 4
gpt4 key购买 nike

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

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

我也尝试了给定链接中的第一个答案:- Drop rows with a 'question mark' value in any column in a pandas dataframe

但是我得到一个错误

~/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

关于python - 如果包含问号 Python 3,则删除 Dataframe 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52005525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com