w3resource

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

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]

Explanation:

series1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
series2 = pd.Series([1, 3, 5, 7, 10])

The above code creates two Pandas Series objects 'series1' and 'series2'. 'series1' contains integers from 1 to 10, and 'series2' contains integers 1, 3, 5, 7, 10.

result = [pd.Index(series1).get_loc(i) for i in series2]: This line uses a list comprehension to create a new list 'result' containing the indices of the elements in 'series1' that match the values in 'series2'.

The pd.Index(series1) function is used to convert the values in 'series1' into an index object. The .get_loc() method is then applied to the index object to get the position of each value in the index. The result is a list of indices that correspond to the positions of the values in 'series2' in 'series1'.

Python-Pandas 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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/python-pandas-data-series-exercise-23.php