1

The following code find index where df['A'] == 1

import pandas as pd
import numpy as np
import random

index = range(10)
random.shuffle(index)
df = pd.DataFrame(np.zeros((10,1)).astype(int), columns = ['A'], index = index)

df.A.iloc[3:6] = 1
df.A.iloc[6:] = 2

print df

print df.loc[df['A'] == 1].index.tolist()

It returns pandas index correctly. How do I get the integer index ([3,4,5]) instead using pandas API?

   A
8  0
4  0
6  0
3  1
7  1
1  1
5  2
0  2
2  2
9  2
[3, 7, 1]
1
  • These are called 'row-indices. Commented Oct 12, 2016 at 20:19

3 Answers 3

4

what about?

In [12]: df.index[df.A == 1]
Out[12]: Int64Index([3, 7, 1], dtype='int64')

or (depending on your goals):

In [15]: df.reset_index().index[df.A == 1]
Out[15]: Int64Index([3, 4, 5], dtype='int64')

Demo:

In [11]: df
Out[11]:
   A
8  0
4  0
6  0
3  1
7  1
1  1
5  2
0  2
2  2
9  2

In [12]: df.index[df.A == 1]
Out[12]: Int64Index([3, 7, 1], dtype='int64')

In [15]: df.reset_index().index[df.A == 1]
Out[15]: Int64Index([3, 4, 5], dtype='int64')
Sign up to request clarification or add additional context in comments.

Comments

2

Here is one way:

df.reset_index().index[df.A == 1].tolist()

This re-indexes the data frame with [0, 1, 2, ...], then extracts the integer index values based on the boolean mask df.A == 1.


Edit Credits to @Max for the index[df.A == 1] idea.

Comments

1

No need for numpy, you're right. Just pure python with a listcomp:

Just find the indexes where the values are 1

print([i for i,x in enumerate(df['A'].values) if x == 1])

4 Comments

I'm looking for a way to do this in pandas. Shouldn't this be implemented in pandas?
I wouldn't know. Your first question mentionned "no numpy", not "with pandas". I'm just proposing a python-only solution.
My bad, I was not expressing myself well at first haha
not a problem. Now there are 3 valid answers which have their own qualities :)

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.