Jeff Saltfist
Jeff Saltfist

Reputation: 943

Get index when looping through one column of pandas

I have a simple dataframe:

index, a, y 0 , 1, 2 1 , 4, 6 2 , 5, 8

I want to loop through the "a" column, and print out its index for a specific value.

for x in df.a:
    if x == 4:
        print ("Index of that row")

What syntax should I use to obtain the index value when the for loop hits the specific value in the "a" column that I am seeking?

Thank You

Upvotes: 6

Views: 18330

Answers (2)

Demetri Pananos
Demetri Pananos

Reputation: 7404

Use

df[df.a==4].index.values

to get an array of those indices

Upvotes: 7

user2285236
user2285236

Reputation:

A series is like a dictionary, so you can use the .iteritems method:

for idx, x in df['a'].iteritems():
    if x==4:
        print('Index of that row: {}'.format(idx))

Upvotes: 15

Related Questions