2

I have a data frame in this format

       A    B     C      D

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

I'm looking to get all ( index , column ) pairs based on certain value of a row using data frame operations. All ( index, column, row value ) pairs will be unique.

I looked in to this question: pythonic way to get index,column for value == 1

Although it's the exact same question as mine, the accepted answer to that question is kind of vague and I couldn't get what I was looking for based on those answers.

I also looked in to similar ones:

a) Select specific index, column pairs from pandas dataframe

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

I tried this:

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

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

I was able to get index values, and column values separately but confused on how to combine them properly.

If I choose row value "a" I expected to get [(1,A), (1,B) , (2,C), (2,D), (3,B), (3,D)]

Any help is highly appreciated. TIA.

Amith Adiraju
  • 306
  • 4
  • 18

1 Answers1

1

One way with where and stack:

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

Output:

array([(1, 'A'), (1, 'B'), (2, 'C'), (2, 'D'), (3, 'B'), (3, 'D')],
  dtype=object)
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74