2017-09-17 63 views
1

我有一个Pandas DataFrame,其中某些值缺失(用?表示)。有没有简单的方法删除所有行中至少有一列的值为?从包含问号的数据框中删除所有行(?)

通常,我会做布尔索引,但我有很多列。一种方法是如下:

for index, row in df.iterrows(): 
    for col in df.columns: 
     if '?' in row[col]: 
      #delete row 

但这似乎unPythonic ...

任何想法?

回答

1

方案1A
boolean indexingany

df 
    col1 col2 col3 col4 
row1 65 24 47 ? 
row2 33 48 ? 89 
row3 ? 34 67 ? 
row4 24 12 52 17 

(df.astype(str) == '?').any(1) 
row1  True 
row2  True 
row3  True 
row4 False 
dtype: bool 

df = df[~(df.astype(str) == '?').any(1)] 
df 
    col1 col2 col3 col4 
row4 24 12 52 17 

这里,astype(str)检查是为了防止TypeError: Could not compare ['?'] with block values的,如果你在你的数据框有字符串和数字列的混合物被提出。

可能性1bvalues

(df.values == '?').any(1) 
array([ True, True, True, False], dtype=bool) 

df = df[~(df.values == '?').any(1)] 
df 
    col1 col2 col3 col4 
row4 24 12 52 17 

选项2
df.replacedf.notnull

df.replace('?', np.nan).notnull().all(1) 
row1 False 
row2 False 
row3 False 
row4  True 
dtype: bool 

df = df[df.replace('?', np.nan).notnull().all(1)] 
    col1 col2 col3 col4 
row4 24 12 52 17 

哪个避免直接比较拨打astype(str)。或者,你可能会做如温家宝建议,只是把它们:

df.replace('?', np.nan).dropna() 
1

或者只是replace它楠使用dropna

df.replace({'?':np.nan}).dropna() 
Out[126]: 
    col1 col2 col3 col4 
row4 24 12 52 17 
0

您可以使用boolean indexingall进行检查,如果值不包含?

  • 如果混合类型 - 数字与int s:
df = pd.DataFrame({'B':[4,5,'?',5,5,4], 
        'C':[7,'?',9,4,2,3], 
        'D':[1,3,5,7,'?',0], 
        'E':[5,3,'?',9,2,4]}) 

print (df) 
    B C D E 
0 4 7 1 5 
1 5 ? 3 3 
2 ? 9 5 ? 
3 5 4 7 9 
4 5 2 ? 2 
5 4 3 0 4 

df = df[(df.astype(str) != '?').all(axis=1)].astype(int) 
print (df) 
    B C D E 
0 4 7 1 5 
3 5 4 7 9 
5 4 3 0 4 

或者与由values创建numpy的阵列比较:

df = df[(df.values != '?').all(axis=1)] 
print (df) 
    B C D E 
0 4 7 1 5 
3 5 4 7 9 
5 4 3 0 4 
  • 如果所有值都是字符串溶液可以简化:
df = pd.DataFrame({'B':[4,5,'?',5,5,4], 
        'C':[7,'?',9,4,2,3], 
        'D':[1,3,5,7,'?',0], 
        'E':[5,3,'?',9,2,4]}).astype(str) 


df = df[(df != '?').all(axis=1)].astype(int) 
print (df) 
    B C D E 
0 4 7 1 5 
3 5 4 7 9 
5 4 3 0 4 
相关问题