w3resource

Python Pandas: Get the positions of items of a given series in another given series

Python Pandas: Data Series Exercise-23 with Solution

Write a Pandas program to get the positions of items of a given series in another given series.

Sample Solution :

Python Code :

import pandas as pd
series1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
series2 = pd.Series([1, 3, 5, 7, 10])
print("Original Series:")
print(series1)
print(series2)
result = [pd.Index(series1).get_loc(i) for i in series2]
print("Positions of items of series2 in series1:")
print(result)

Sample Output:

Original Series:
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10
dtype: int64
0     1
1     3
2     5
3     7
4    10
dtype: int64
Positions of items of series2 in series1:
[0, 2, 4, 6, 9]

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to extract items at given positions of a given series.
Next: Write a Pandas program convert the first and last character of each word to upper case.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Membership Testing in a Collection

>>> a = ('one', 'two', 'three', 'four', 'five')
>>> if 'one' in a:
...     print('The tuple contains one.')
... 
The tuple contains one.
>>> b = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> if 2 in b.keys():
...     print('The dict has the key of 2.')
... 
The dict has the key of 2.