基于行中的值检索对(索引,列)对

问题描述 投票:0回答:1

我有这种格式的数据框

       A    B     C      D

1      a    a     c      c 
2      c    b     a      a 
3      b    a     c      a
.
.
.

我希望使用数据帧操作基于行的特定值来获取所有(索引,列)对。所有(索引,列,行值)对都是唯一的。

我调查了这个问题:pythonic way to get index,column for value == 1

尽管与我的问题完全相同,但对该问题的公认答案有点含糊,我无法根据这些答案得到想要的东西。

我也看过类似的东西:

a)Select specific index, column pairs from pandas dataframe

b)Python Pandas: Get index of rows which column matches certain value

我尝试过:

req_cols = df.columns [ ( new_df == "a" ).any() ]

req_inds = (df == "a").index

我能够分别获取索引值和列值,但是对于如何正确组合它们感到困惑。

如果选择行值“ a”,我希望得到[(1,A), (1,B) , (2,C), (2,D), (3,B), (3,D)]

非常感谢您的帮助。 TIA。

python pandas indexing
1个回答
1
投票

wherestack的一种方法:

df.where(df.eq('a')).stack().index.values

输出:

array([(1, 'A'), (1, 'B'), (2, 'C'), (2, 'D'), (3, 'B'), (3, 'D')],
  dtype=object)
© www.soinside.com 2019 - 2024. All rights reserved.