How to find the positions of multiples of a number in a Pandas Series?

I was searching for a solution to a problem that involved getting the index positions of multiples of a number in a series, for example, if I have the following series and I want to find the positions of multiples of 3:

my_series = [1, 3, 5, 6, 8, 9]

My desired output would be:


I did find a solution that involved using NumPy’s np.where() function that returns the indexes of the elements that satisfy a given condition but are there alternative methods for doing the same thing? Here is the np.where() code I used:

1 Like

@mubashir_rizvi, I have a simple method in which we iterate over the index attribute of the series using list comprehension and checking for multiples of 3 using the modulo (%) operator. Here is the code below for your better understanding:

I hope the above explanation helps you. Let me know if you have any confusion.

Hi @mubashir_rizvi you can use the built-in filter() function in Python along with a lambda function to create a list of positions where the condition is true.

Here’s an example using your series:

This will output: [1, 3, 5], which are the positions of the multiples of 3 in the series.

I hope this helps! Let me know if you have any questions.

Hey @mubashir_rizvi , you can use apply() function in Pandas to apply a function to a DataFrame or Series along a specified axis. In the given example code, a lambda function is used with apply() to filter out all values that are not multiples of 3, resulting in a new Series. The dropna() function is then applied to remove any NaN values from the Series, and the index attribute is used to obtain the index of the remaining values.