根据行中的值检索(索引,列)对

我有这种格式的数据框

       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),D),(3,D)]

我们非常感谢您的帮助。 TIA。

banqiansheng 回答:根据行中的值检索(索引,列)对

使用wherestack的一种方式:

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

输出:

array([(1,'A'),(1,'B'),(2,'C'),'D'),(3,'D')],dtype=object)
本文链接:https://www.f2er.com/3134643.html

大家都在问