我有一个名为train_data的数据帧。
这是每列的数据类型。

列workclass、occupation和native-country的数据类型为"Object“,其中一些行包含值"?”。

在本例中,您可以看到行索引5包含一些带有"?“的值。
我想删除所有包含任何"?“的单元格的行。
我尝试了以下代码,但它不起作用。
train_data = train_data[~(train_data.values == '?').any(1)]
train_data发布于 2021-04-06 16:33:11
使用.loc进行索引切片。
import pandas as pd
df1 = pd.DataFrame({'A' : [0,1,2,3,'?'],
'B' : [2,4,5,'?',9],
'C' : [0,'?',2,3,4]})
print(df1)
A B C
0 0 2 0
1 1 4 ?
2 2 5 2
3 3 ? 3
4 ? 9 4print(df1.loc[~df1.eq('?').any(1)])
A B C
0 0 2 0
2 2 5 2如果只想检查object列,请使用
pd.select_dtypes
df1.select_dtypes('object').eq('?').any(1)
0 False
1 True
2 False
3 True
4 True
dtype: bool编辑。
一种处理前导或尾随空格的方法。
df1 = pd.DataFrame({'A' : [0,1,2,3,'?'],
'B' : [2,4,5,' ?',9],
'C' : [0,'? ',2,3,4]})
df1.eq('?').any(1)
0 False
1 False
2 False
3 False
4 True
dtype: bool
df1.replace('(\s+\?)|(\?\s+)',r'?',regex=True).eq('?').any(1)
0 False
1 True
2 False
3 True
4 True
dtype: bool带lambda的str.strip()
str_cols = df1.select_dtypes('object').columns
df1[str_cols] = df1[str_cols].apply(lambda x : x.str.strip())
df1.eq('?').any(1)
0 False
1 True
2 False
3 True
4 True
dtype: boolhttps://stackoverflow.com/questions/66965142
复制相似问题