简体   繁体   中英

Is there a way of extracting indices from a pandas DataFrame based on value

I have the following DataFrame:

index col0 col1 col2
0     0    1    0
1     1    0    1
2     0    1    1

I would like to extract the following indices(those that contain ones(or any value)):

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

Is there a method in pandas that can do this?

Use np.where + zip


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

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

Here is one way

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)]

You could use numpy.nonzero :

result = list(zip(*np.nonzero(df.values)))
print(result)

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM