[英]Is there a way of extracting indices from a pandas DataFrame based on value
I have the following DataFrame:我有以下 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? pandas 中是否有可以做到这一点的方法?
Use np.where
+ zip
使用
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 :您可以使用numpy.nonzero :
result = list(zip(*np.nonzero(df.values)))
print(result)
Output Output
[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.