2017-08-03 50 views
0
In [3]: import numpy as np 

In [4]: b = pd.DataFrame(np.array([ 
    ...:  [1,np.nan,3,4], 
    ...:  [np.nan, 4, np.nan, 4] 
    ...: ])) 

In [13]: b 
Out[13]: 
    0 1 2 3 
0 1.0 NaN 3.0 4.0 
1 NaN 4.0 NaN 4.0 

我想查找Nan值存在的列名稱和索引。熊貓:我如何找到col值,存在Nan值的索引?

例如,「b具有index 0, col1NaN值,index 0, col0index 1 col2

我已經試過:

In [14]: b[b.isnull()] 
Out[14]: 
    0 1 2 3 
0 NaN NaN NaN NaN 
1 NaN NaN NaN NaN 

=>我不知道爲什麼顯示DataFrame填充NaN

In [15]: b[b[0].isnull()] 
Out[15]: 
    0 1 2 3 
1 NaN 4.0 NaN 4.0 

=>這隻能說明DataFrame其中Nan價值column 0存在部分..

我怎樣才能

回答

3

你可以使用np.where找到索引,其中pd.isnull(b)爲真:

import numpy as np 
import pandas as pd 

b = pd.DataFrame(np.array([ 
    [1,np.nan,3,4], 
    [np.nan, 4, np.nan, 4]])) 

idx, idy = np.where(pd.isnull(b)) 
result = np.column_stack([b.index[idx], b.columns[idy]]) 
print(result) 
# [[0 1] 
# [1 0] 
# [1 2]] 

或使用DataFrame.stack通過移動來重新塑造DataFrame列標籤到索引中。 這將創建一個系列是真正的地方b爲空:

mask = pd.isnull(b).stack() 
# 0 0 False 
# 1  True 
# 2 False 
# 3 False 
# 1 0  True 
# 1 False 
# 2  True 
# 3 False 

,然後讀出從多指標的行和列標籤:

print(mask.loc[mask]) 
# 0 1 True 
# 1 0 True 
# 2 True 
# dtype: bool 

print(mask.loc[mask].index.tolist()) 
# [(0, 1), (1, 0), (1, 2)]