Reputation: 15
Sorry for the confusing title, but i dont know how to explain this without an example.
I need to get a list of positions of items from one series in another series. The example i was give is the following:
ser1 = pandas.Series([10, 9, 6, 5, 3, 1, 12, 8, 13])
ser2 = pandas.Series([1, 3, 10, 13])
The solution should be [5, 4, 0, 8]
I first thought of using numpy.where(ser1.isin(ser2))
but the array of idex i get is in the wrong order: [0, 4, 5, 8]
If I use ser2.isin(ser1)
, i get an array of boolean values. Is there a way to get the index of elements instead of this? Or any other way to solve this using other methods?
Upvotes: 1
Views: 598
Reputation: 862406
Use broadcasting in numpy for compare with argmax
for correct ordering:
out = (ser2.to_numpy() == ser1.to_numpy()[:, None]).argmax(axis=0)
[5, 4, 0, 8]
Solution if some value not matched with np.where
and any
:
ser1=pd.Series([10, 9, 6, 1, 3, 1, 12, 8, 13])
ser2 = pd.Series([1, 3, 10, 130])
m = ser2.to_numpy() == ser1.to_numpy()[:, None]
out = np.where(m.any(axis=0), m.argmax(axis=0), np.nan)
print (out)
[ 3. 4. 0. nan]
Upvotes: 1