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.

1

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.