w3resource

Pandas Data Series: Find the positions of numbers that are multiples of 5 of a given series

Pandas: Data Series Exercise-21 with Solution

Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series.

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
num_series = pd.Series(np.random.randint(1, 10, 9))
print("Original Series:")
print(num_series)
result = np.where(num_series % 5==0)
print("Positions of numbers that are multiples of 5:")
print(result)

Sample Output:

Original Series:
0    1
1    9
2    8
3    6
4    9
5    7
6    1
7    1
8    1
dtype: int64
Positions of numbers that are multiples of 5:
[]        

Explanation:

num_series = pd.Series(np.random.randint(1, 10, 9)): This code creates a Pandas series object 'num_series' containing 9 random integers between 1 and 10 using the np.random.randint() method.

result = np.where(num_series % 5==0): This code uses the np.where() function to create a boolean mask that checks which values in the Pandas Series object 'num_series' are divisible by 5. The resulting boolean mask will have the same length as the original Series object, with True values at the positions where the corresponding value in the Series object is divisible by 5, and False values otherwise.

The output of np.where() function returns a tuple containing the indices of the True values in the boolean mask.

The output of print(result) will depend on the random integers generated by the NumPy function np.random.randint().

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 extract items at given positions of a 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-21.php