Reputation: 2245
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
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