How to get the positions of items of series ser2 in another series ser1? Input: ser1 =…
- User
How to get the positions of items of series ser2 in another series ser1? Input: ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13]) ser2 = pd.Series([1, 3, 10, 13]) Desired output: [5, 4, 0, 8]
- Assistant
To find the positions of items from
ser2inser1, you can use thepd.Series.get_indexermethod in pandas. Here's how you can do it:import pandas as pd # Defining the Series ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13]) ser2 = pd.Series([1, 3, 10, 13]) # Getting the positions of items of ser2 in ser1 positions = ser1.index[ser1.isin(ser2)].tolist() # Validate the positions result = [ser1.index[ser1 == item][0] for item in ser2] print(result)Explanation:
- We have two pandas Series:
ser1andser2. - We find the indices of the elements of
ser2inser1using the comparison and theindexmethod. - Using a list comprehension, we traverse each item in
ser2, and for each item, we find its index inser1. - Finally, print the result.
Output:
This will give you the desired output:
[5, 4, 0, 8]This means that:
- The value
1from is at position in .
- We have two pandas Series:
- User
Good, but I got not a very 'beautiful' output: [np.int64(5), np.int64(4), np.int64(0), np.int64(8)]
- Assistant
If you'd like the output to be a list of standard Python integers instead of
numpy.int64, you can convert the positions to native Python integers while constructing the final list. Here's an updated version of the previous code that does that:import pandas as pd # Defining the Series ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13]) ser2 = pd.Series([1, 3, 10, 13]) # Getting the positions of items of ser2 in ser1 result = [int(ser1.index[ser1 == item][0]) for item in ser2] print(result)Explanation of Changes:
- By using
int()when constructing theresultlist, you ensure that the integers are converted fromnumpy.int64to standard Python integers.
Output:
Now, you will get the output in a more native and cleaner format:
[5, 4, 0, 8]This way, the output will be simple Python integers, which might be more suitable for your needs!
- By using