[英]Retrieve indices of NaN values in a pandas dataframe
我嘗試為包含 NaN 值的每一行檢索相應列的所有索引。
d=[[11.4,1.3,2.0, NaN],[11.4,1.3,NaN, NaN],[11.4,1.3,2.8, 0.7],[NaN,NaN,2.8, 0.7]]
df = pd.DataFrame(data=d, columns=['A','B','C','D'])
print df
A B C D
0 11.4 1.3 2.0 NaN
1 11.4 1.3 NaN NaN
2 11.4 1.3 2.8 0.7
3 NaN NaN 2.8 0.7
我已經完成了以下操作:
我想要的(最好是列的名稱)是得到這樣的列表:
[ ['D'],['C','D'],['A','B'] ]
希望我能找到一種方法而無需對每一行進行每一列的測試
if df.ix[i][column] == NaN:
我正在尋找一種 pandas 方法來處理我龐大的數據集。
提前致謝。
使用scipy坐標格式稀疏矩陣檢索空值的坐標應該是高效的:
import scipy.sparse as sp
x,y = sp.coo_matrix(df.isnull()).nonzero()
print(list(zip(x,y)))
[(0, 3), (1, 2), (1, 3), (3, 0), (3, 1)]
請注意,我正在調用nonzero
方法,以便只輸出基礎稀疏矩陣中非零項的坐標,因為我不關心全部為True
的實際值。
另一種方法,提取NaN行:
In [11]: df_null = df.isnull().unstack()
In [12]: t = df_null[df_null]
In [13]: t
Out[13]:
A 3 True
B 3 True
C 1 True
D 0 True
1 True
dtype: bool
這可以幫助你完成大部分工作。
雖然使用該系列可能更容易:
In [14]: s = pd.Series(t2.index.get_level_values(1), t2.index.get_level_values(0))
In [15]: s
Out[15]:
0 D
1 C
1 D
3 A
3 B
dtype: object
例如,如果你想要列表(雖然我認為你不需要它們)
In [16]: s.groupby(level=0).apply(list)
Out[16]:
0 [D]
1 [C, D]
3 [A, B]
dtype: object
您可以遍歷數據框中的每一行,創建一個空值掩碼,並輸出它們的索引(即數據框中的列)。
lst = []
for _, row in df.iterrows():
mask = row.isnull()
lst += [row[mask].index.tolist()]
>>> lst
[['D'], ['C', 'D'], [], ['A', 'B']]
另一種更簡單的方法是:
>>>df.isnull().any(axis=1)
0 True
1 True
2 False
3 True
dtype: bool
子集:
>>> bool_idx = df.isnull().any(axis=1)
>>> df[bool_idx]
A B C D
0 11.4 1.3 2.0 NaN
1 11.4 1.3 NaN NaN
3 NaN NaN 2.8 0.7
獲取整數索引:
>>> df[bool_idx].index
Int64Index([0, 1, 3], dtype='int64')
嘗試使用:
s = df.isna().any()
它返回一系列 boolean 值,表示列具有NaN值。 索引是列名。
然后使用檢索NaN列
s[s==True].index[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.