我有以下数据框:
index col0 col1 col2
0 0 1 0
1 1 0 1
2 0 1 1
我希望提取包含1(或任何值)的索引,如下所示:
[(0, 1), (1, 0), (1, 2), (2, 1), (2,2))]
有没有 pandas 中的方法可以实现这个功能?
使用 np.where
+ zip
[*zip(*np.where(df))]
[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]
df.columns=np.arange(df.shape[1])
df.stack().loc[lambda x : x==1].index.tolist()
[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]
result = list(zip(*np.nonzero(df.values)))
print(result)
输出
[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]