[英]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.