簡體   English   中英

有沒有一種方法可以根據值從 pandas DataFrame 中提取索引

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM