Advanced Uses of NumPy Arrays
Some advanced uses of NumPy arrays:
- Fancy indexing: This allows you to select elements from an array using a more complex criteria than simple slicing. For example, you can use fancy indexing to select all elements that are greater than a certain value, or all elements that fall within a certain range.
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Select all elements greater than 2
print(arr[arr > 2])
# Output: [3, 4, 5]
# Select all elements in the range [2, 4]
print(arr[2:4])
# Output: [3, 4]
- Universal functions (ufuncs): These are functions that operate element-wise on NumPy arrays. For example, the
sum()
ufunc sums all the elements in an array, and theabs()
ufunc returns the absolute value of each element in an array.
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Sum all the elements in the array
print(np.sum(arr))
# Output: 15
# Find the absolute value of each element in the array
print(np.abs(arr))
# Output: [1, 2, 3, 4, 5]
- Broadcasting: This allows you to perform operations between arrays of different shapes. For example, you can add a scalar to an array, or add two arrays of different shapes.
Python
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Add a scalar to each element in the array
print(arr1 + 2)
# Output: [3, 4, 5]
# Add two arrays of different shapes
print(arr1 + arr2)
# Output: [5, 7, 9]
- Masked arrays: These are arrays that contain a mask, which is an array of boolean values that indicate which elements are valid. This can be useful for filtering out invalid data or performing operations only on valid data.
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
mask = arr > 3
# Create a masked array
masked_arr = np.ma.array(arr, mask=mask)
# Print the masked array
print(masked_arr)
# Output: [1 2 NaN]
- Advanced sorting: NumPy provides a variety of sorting methods that allow you to sort arrays in different ways. For example, you can sort by the values in an array, or by the indices of an array.
Python
import numpy as np
arr = np.array([5, 2, 3, 1, 4])
# Sort the array by the values
print(np.sort(arr))
# Output: [1, 2, 3, 4, 5]
# Sort the array by the indices
print(np.argsort(arr))
# Output: [3, 1, 2, 0, 4]
- Linear algebra: NumPy provides a comprehensive library of linear algebra functions, such as matrix multiplication, inverse, and determinant. For example, the following code calculates the inverse of the matrix
arr
:
Python
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(np.linalg.inv(arr))
Output:
[[-2/7 1/7]
[1/7 -1/7]]
These are just a few of the many advanced uses of NumPy arrays.
Comments
Post a Comment