Sorting Arrays
Sorting is essential for data analysis, ranking, and organizing datasets.
Sorting a 1D Array
a = np.array([3, 1, 4, 1, 5])
print("Original Array:", a)
print("Sorted Array:", np.sort(a))
# Sorts in ascending order
Sorting a 2D Array
matrix = np.array([[3, 2, 1], [6, 5, 4]])
print("Original Matrix:\n", matrix)
print("Sorted along each row:\n", np.sort(matrix, axis=1)) # Row-wise sorting
print("Sorted along each column:\n", np.sort(matrix, axis=0)) # Column-wise sorting
Searching for Elements in an Array
NumPy provides fast searching operations to find values in an array.
Finding the Index of the Maximum and Minimum Values
a = np.array([3, 1, 4, 1, 5, 9, 2])
print("Index of Maximum Value:", np.argmax(a))
print("Index of Minimum Value:", np.argmin(a))
# Returns index of max value
# Returns index of min value
Finding Elements that Satisfy a Condition
a = np.array([10, 20, 30, 40, 50])
# Find elements greater than 25
filtered_elements = a[a > 25]
print("Elements greater than 25:", filtered_elements)
Why is Searching Important?
- Used in data preprocessing to filter values in large datasets.
- Helps in feature selection and anomaly detection in machine learning.