在 pandas 数据框中的任何列中删除带有“问号”值的行 [英] Drop rows with a 'question mark' value in any column in a pandas dataframe
本文介绍了在 pandas 数据框中的任何列中删除带有“问号”值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除任何列中的所有行(或不带任何行)。我还想将元素更改为 float 类型。
I want to remove all rows (or take all rows without) a question mark symbol in any column. I also want to change the elements to float type.
输入:
X Y Z
0 1 ?
1 2 3
? ? 4
4 4 4
? 2 5
输出:
X Y Z
1 2 3
4 4 4
最好使用pandas数据框操作。
Preferably using pandas dataframe operations.
推荐答案
您可以先尝试找到字符串?
列中,创建布尔掩码并最后过滤行-使用布尔索引。如果需要将列转换为 float
,请使用 astype
:
You can try first find string ?
in columns, create boolean mask and last filter rows - use boolean indexing. If you need convert columns to float
, use astype
:
print ~((df['X'] == '?' ) (df['Y'] == '?' ) | (df['Z'] == '?' ))
0 False
1 True
2 False
3 True
4 False
dtype: bool
df1 = df[~((df['X'] == '?' ) | (df['Y'] == '?' ) | (df['Z'] == '?' ))].astype(float)
print df1
X Y Z
1 1 2 3
3 4 4 4
print df1.dtypes
X float64
Y float64
Z float64
dtype: object
或者您可以尝试:
df['X'] = pd.to_numeric(df['X'], errors='coerce')
df['Y'] = pd.to_numeric(df['Y'], errors='coerce')
df['Z'] = pd.to_numeric(df['Z'], errors='coerce')
print df
X Y Z
0 0 1 NaN
1 1 2 3
2 NaN NaN 4
3 4 4 4
4 NaN 2 5
print ((df['X'].notnull() ) & (df['Y'].notnull() ) & (df['Z'].notnull() ))
0 False
1 True
2 False
3 True
4 False
dtype: bool
print df[ ((df['X'].notnull() ) & (df['Y'].notnull() ) & (df['Z'].notnull() )) ].astype(float)
X Y Z
1 1 2 3
3 4 4 4
更好地使用:
df = df[(df != '?').all(axis=1)]
或:
df = df[~(df == '?').any(axis=1)]
这篇关于在 pandas 数据框中的任何列中删除带有“问号”值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文