w3resource

Pandas Data Series: Create a subset of a given series based on value and condition

Pandas: Data Series Exercise-13 with Solution

Write a Pandas program to create a subset of a given series based on value and condition.

Sample Solution :

Python Code :

import pandas as pd
s = pd.Series([0,1,2,3,4,5,6,7,8,9,10])
print("Original Data Series:")
print(s)
print("\nSubset of the above Data Series:")
n = 6
new_s = s[s < n]
print(new_s)

Sample Output:

Original Data Series:
0      0
1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10    10
dtype: int64

Subset of the above Data Series:
0    0
1    1
2    2
3    3
4    4
5    5
dtype: int64                   

Explanation:

In the above exercise -

  • s = pd.Series([0, 1,2,3,4,5,6,7,8,9,10]): This line creates a Pandas Series object 's' containing a sequence of 11 integer values from 0 to 10.
  • new_s = s[s < n]: This line creates a new Pandas Series object 'new_s' by selecting the elements from the original Series object 's' that are less than a specified integer value 'n'. Here the value of n = 6. This is done by applying a boolean mask to the original Series object using the condition s < n.
  • The resulting Series object 'new_s' will contain only the elements from the original Series object 's' that are less than 6.

Python-Pandas Code Editor:

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

Previous: Write a Pandas program to add some data to an existing Series.
Next: Write a Pandas program to change the order of index of a given series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.