Troy D
Troy D

Reputation: 2245

Pandas get positions of intersection between 2 indexes

If I have 2 Pandas dataframe indexes, idx1 and idx2, how I can get the index positions (from the original indexes) of the intersection:

idx1 = pd.Index([1, 2, 3, 4])
idx2 = pd.Index([3, 4, 5, 6])
intersect = idx1.intersection(idx2)

Looking for [2, 3] for idx1 and [0, 1] for idx 2.

This doesn't work:

idx1.get_loc(intersect)

I can do a loop to get these values, but is there something better?

for x in intersect:
    print(idx1.get_loc(x))

Upvotes: 1

Views: 632

Answers (1)

akuiper
akuiper

Reputation: 215117

If the index is unique, you can use get_indexer:

idx1.get_indexer(intersect)
# array([2, 3])

idx2.get_indexer(intersect)
# array([0, 1])

If the index is not unique, then you need isin method with numpy.where:

pd.np.where(idx1.isin(intersect))[0]
# array([2, 3])

pd.np.where(idx2.isin(intersect))[0]
# array([0, 1])

Upvotes: 3

Related Questions