[英]Extracting a single value from a Pandas Dataframe based on info in other column
[英]Is there a way of extracting indices from a pandas DataFrame based on value
我有以下 DataFrame:
index col0 col1 col2
0 0 1 0
1 1 0 1
2 0 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)]
您可以使用numpy.nonzero :
result = list(zip(*np.nonzero(df.values)))
print(result)
Output
[(0, 1), (1, 0), (1, 2), (2, 1), (2, 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.