Obtain Positions of Multiples of 3 in a Series

This thread focuses on different methods of getting the index positions of elements or values which are multiples of 3 from a series. You can also use and apply the same methods discussed in this thread for finding index positions of different numbers and their multiples. Here are the methods for achieving this task along with a simple example code for each method to help you understand the methods easily:

1. Using "np.where()" method:

  • The np.where() is a NumPy function that returns the indices of the elements in an input array that satisfy a given condition.
  • In the example below, a simple condition is used to filter elements that are multiples of 3.

2. Using "index" attribute and condition:

  • 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.

3. Using "apply()" method:

  • The apply() function in Pandas is used to apply a function along an axis of a DataFrame or a Series.
  • In the example below, a lambda function is used to return the value if it is a multiple of 3 and return NaN if it’s not. The dropna() function is applied on the new series to drop all NaN values and finally get the index using the index attribute.

4. Using Pandas "where()" method:

  • Pandas where() function is similar to the NumPy where() function.
  • The Pandas where() function is used to return a new DataFrame or Series with the same shape as the input DataFrame or Series but with values replaced with NaN where the condition is False.
  • The dropna() function is then applied on the new series to drop all NaN values and get the index using the index attribute.