'Get (index,column) pair where the value is True
Say I have a dataframe df
a b c
0 False True True
1 False False False
2 True True False
3 False False False
I would like all (index,column) pairs e.g (0,"b"),(0,"c),(2,"a"),(2,"b") where the True value is.
Is there a way to do that, without looping over either the index or columns?
Solution 1:[1]
Assuming booleans in the input, you can use:
df.where(df).stack().index.to_list()
output:
[(0, 'b'), (0, 'c'), (2, 'a'), (2, 'b')]
Solution 2:[2]
Let us try np.where:
r, c = np.where(df)
[*zip(df.index[r], df.columns[c])]
[(0, 'b'), (0, 'c'), (2, 'a'), (2, 'b')]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
| Solution 2 | Shubham Sharma |
