w3resource

Pandas Data Series: Extract items at given positions of a given series

Pandas: Data Series Exercise-22 with Solution

Write a Pandas program to extract items at given positions of a given series.

Sample Solution :

Python Code :

import pandas as pd
num_series = pd.Series(list('2390238923902390239023'))
element_pos = [0, 2, 6, 11, 21]
print("Original Series:")
print(num_series)
result = num_series.take(element_pos)
print("\nExtract items at given positions of the said series:")
print(result)

Sample Output:

Original Series:
0     2
1     3
2     9
3     0
4     2
5     3
6     8
7     9
8     2
9     3
10    9
11    0
12    2
13    3
14    9
15    0
16    2
17    3
18    9
19    0
20    2
21    3
dtype: object

Extract items at given positions of the said series:
0     2
2     9
6     8
11    0
21    3
dtype: object

Explanation:

num_series = pd.Series(list('2390238923902390239023')): This code creates a Pandas Series object 'num_series' containing a string of digits.

element_pos = [0, 2, 6, 11, 21]: This code creates a Python list ‘element_pos’ containing the positions of the elements in the Pandas Series object 'num_series' that we want to extract. In this case, the positions are [0, 2, 6, 11, 21].

result = num_series.take(element_pos): This code creates a new Pandas Series object 'result' by extracting the elements in 'num_series' that correspond to the indices specified in the list element_pos. This is done using the .take() method, which takes a list of indices and returns a new Series object containing the elements at those indices.

Python-Pandas Code Editor:

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

Previous: Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series.
Next: Write a Pandas program to get the positions of items of a given series in another given series.

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-22.php