0

Consider the data frame

   c1   c2   c3  
0 a 3    4    2  
1 b 1    2    7  

say I want to know which column in row 1 has the element 7. how will I achieve it? I am trying to achieve it using pandas.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Akshay .K
  • 13
  • 4
  • I would recommend reading the thread posted below, it will make a big difference on how people help you. https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – Brian Jan 18 '18 at 14:18

2 Answers2

1

If want get column of first value in row with index 1:

a = df.loc[1].eq(7).idxmax()
print (a)
c3

Explanation:

First select column with index by loc:

print (df.loc[1])
c1    4
c2    2
c3    7
Name: (1, b), dtype: int64

Compare with 7:

print (df.loc[1].eq(7))
c1    False
c2    False
c3     True
Name: (1, b), dtype: bool

and for c3 get index of max value, it means first True.

If row contains multiple values (here 7) and need all matched columns use boolean indexing:

a = df.loc[1].eq(7)
a = a.index[a].tolist()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

Not sure exactly what output you're looking for, but I believe this will help. I started by creating your dataframe.

df = pd.DataFrame({'c1':['3', '1'],
                   'c2':['4', '2'],
                   'c3':['2', '7']})

The following code reads like so: give me all the records where the column 'c3' equals 7.

df = df[df['c3'] == '7']

Output:

enter image description here

Brian
  • 2,163
  • 1
  • 14
  • 26