Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding the multiples of a number in a given list using NumPy
Finding multiples of a number in a list is a common task in data analysis. NumPy provides efficient methods to identify multiples using vectorized operations and built-in functions like argwhere() and modulo operations.
Using Basic Loop Method
The traditional approach uses a loop to check each element ?
import numpy as np
listnum = np.arange(1, 20)
multiples = []
n = 5
print("NumList:", listnum)
for num in listnum:
if num % n == 0:
multiples.append(num)
print("Multiples of {} are {}".format(n, multiples))
NumList: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Multiples of 5 are [5, 10, 15]
Using NumPy Vectorized Operations
NumPy's vectorized operations are more efficient for large arrays ?
import numpy as np
listnum = np.arange(1, 20)
n = 5
# Find multiples using boolean indexing
mask = listnum % n == 0
multiples = listnum[mask]
print("NumList:", listnum)
print("Multiples of {} are {}".format(n, multiples))
NumList: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Multiples of 5 are [ 5 10 15]
Finding Index Positions with argwhere()
To get both values and their index positions, use np.argwhere() ?
import numpy as np
listnum = np.arange(1, 20)
n = 5
# Find indices where multiples exist
indices = np.argwhere(listnum % n == 0).flatten()
multiples = listnum[indices]
print("NumList:", listnum)
print("Indices of multiples of {}: {}".format(n, indices))
print("Multiples of {} are: {}".format(n, multiples))
NumList: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Indices of multiples of 5: [ 4 9 14] Multiples of 5 are: [ 5 10 15]
Using where() Function
NumPy's where() function provides another efficient approach ?
import numpy as np
listnum = np.arange(1, 20)
n = 3
# Using np.where() to find indices and values
indices = np.where(listnum % n == 0)[0]
multiples = listnum[indices]
print("NumList:", listnum)
print("Multiples of {} at indices {}: {}".format(n, indices, multiples))
NumList: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Multiples of 3 at indices [ 2 5 8 11 14 17]: [ 3 6 9 12 15 18]
Comparison
| Method | Performance | Best For |
|---|---|---|
| Loop | Slower | Small arrays, learning |
| Boolean indexing | Fast | Getting values only |
argwhere() |
Fast | Getting indices and values |
where() |
Fast | Complex conditions |
Conclusion
Use NumPy's vectorized operations for efficient multiple finding. Boolean indexing is simplest for values, while argwhere() and where() provide index information for more complex analysis.
Advertisements
