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]

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

Returns a list with n elements removed from the beginning

Example:

def tips_take(itr, n = 1):
  return itr[:n]
print(tips_take([1, 2, 3], 5))
print(tips_take([1, 2, 3], 0))

Output:

[1, 2, 3]
[]