2017-07-27 770 views
2

我試圖運行我認爲簡單的代碼來消除所有NaN中的任何列,但無法使其正常工作(axis = 1在刪除行時工作正常) :熊貓:IndexingError:不可對齊的布爾系列作爲索引器提供

import pandas as pd 
import numpy as np 

df = pd.DataFrame({'a':[1,2,np.nan,np.nan], 'b':[4,np.nan,6,np.nan], 'c':[np.nan, 8,9,np.nan], 'd':[np.nan,np.nan,np.nan,np.nan]}) 

df = df[df.notnull().any(axis = 0)] 

print df 

完整的錯誤:

raise IndexingError('Unalignable boolean Series provided as 'pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

預期輸出:

 a b c 
0 1.0 4.0 NaN 
1 2.0 NaN 8.0 
2 NaN 6.0 9.0 
3 NaN NaN NaN 

回答

3

你需要loc,因爲按列過濾:

print (df.notnull().any(axis = 0)) 
a  True 
b  True 
c  True 
d False 
dtype: bool 

df = df.loc[:, df.notnull().any(axis = 0)] 
print (df) 

    a b c 
0 1.0 4.0 NaN 
1 2.0 NaN 8.0 
2 NaN 6.0 9.0 
3 NaN NaN NaN 

或過濾列,然後通過[]選擇:

print (df.columns[df.notnull().any(axis = 0)]) 
Index(['a', 'b', 'c'], dtype='object') 

df = df[df.columns[df.notnull().any(axis = 0)]] 
print (df) 

    a b c 
0 1.0 4.0 NaN 
1 2.0 NaN 8.0 
2 NaN 6.0 9.0 
3 NaN NaN NaN 

或者dropna與參數how='all'測試remove僅NaN房間裏擺滿所有列:

print (df.dropna(axis=1, how='all')) 
    a b c 
0 1.0 4.0 NaN 
1 2.0 NaN 8.0 
2 NaN 6.0 9.0 
3 NaN NaN NaN 
+0

Ahhhh,因爲'df []'方法正在尋找一個基於行的索引,而不是一個基於列的索引。收到了。謝謝。 – pshep123

+0

@ pshep123 - 很高興能幫到你! – jezrael

2

您可以使用dropnaaxis=1thresh=1

In[19]: 
df.dropna(axis=1, thresh=1) 

Out[19]: 
    a b c 
0 1.0 4.0 NaN 
1 2.0 NaN 8.0 
2 NaN 6.0 9.0 
3 NaN NaN NaN 

這將下降不具有至少1個非楠值的任何列,這將意味着所有NaN任何列就會被放棄

你嘗試過什麼原因失敗的原因是因爲布爾面膜:

In[20]: 
df.notnull().any(axis = 0) 

Out[20]: 
a  True 
b  True 
c  True 
d False 
dtype: bool 

不能上這就是默認情況下使用,因爲這會產生在列的布爾面具指數對準

+1

謝謝埃德 - 我不知道'thresh'參數。剛剛得知您可以同時使用兩個軸來修剪所有空行和列:'df = df.dropna(axis = [0,1],how ='all')' – pshep123

+0

是的,它是非常靈活和有用的方法 – EdChum