有没有一种基于值从pandas DataFrame中提取索引的方法?

5

我有以下数据框:

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 中的方法可以实现这个功能?
3个回答

7

使用 np.where + zip


[*zip(*np.where(df))]

[(0, 1), (1, 0), (1, 2), (2, 1), (2, 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)]

1
您可以使用 numpy.nonzero
result = list(zip(*np.nonzero(df.values)))
print(result)

输出

[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接