jas_0n
jas_0n

Reputation: 93

How to get index of the first column that satisfies condition

Assuming I have A df like this:

ID | one | two | three  
A  | 1   | 0   |   3  
B  | 3   | 1   |   4  
C  | 4   | 3   |   2  

How can I get the index of the first column where value is greater than 2? So that as a result O could get this kind of relation:

ID | COLNUM  
A  |  3    
B  |  1   
C  |  1

Upvotes: 0

Views: 95

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

You can use np.argmax to get the integer index:

dfB = dfA['ID'].to_frame()

dfB['COLNUM'] = np.argmax(dfA.iloc[:,1:].gt(2).values, axis=1) + 1

Upvotes: 0

luigigi
luigigi

Reputation: 4215

You could use this:

df.set_index('ID').lt(2).idxmin(axis=1)

ID
A    three
B      one
C      one

Upvotes: 1

Related Questions