Operations on NumPy Arrays – Part 2
November 24, 2020 2020-12-03 21:18Operations on NumPy Arrays – Part 2
In the first part of Operations on Numpy Arrays, you learned about slicing, indexing, and arithmetic operations. This chapter will introduce you to some very important operations on NumPy arrays that are requently used in Data Science.
Statistical Operations on NumPy arrays
NumPy contains various in-built functions to get statistical information regarding the array such as max value, min value, mean, median, etc. Below is a list of such functions:
Statistics | Built-In NumPy Functions |
Minimum Value | numpy.min() |
Maximum Value | numpy.max() |
Mean Value | numpy.mean() |
Median Value | numpy.median() |
Standard deviation | numpy.std() |
Get count of Unique values | numpy.unique() |
import numpy as np # Creating a 1-D NumPy array arr1 = np.arange(start=1, stop=5, step=1) # Printing the array print("arr1: ", arr1) # Min value print("Min: ", np.min(arr1)) # Max Value print("Max: ", np.max(arr1)) # Mean print("Mean: ", np.mean(arr1)) # Median print("Median: ", np.median(arr1)) # Standard Deviation print("Standard Deviation: ", np.std(arr1)) # Get unique values and their counts uniqs, counts = np.unique(arr1, return_counts=True) print("Unique values: ", uniqs) print("Count of respective unique values: ", counts)
arr1: [1 2 3 4] Min: 1 Max: 4 Mean: 2.5 Median: 2.5 Standard Deviation: 1.118033988749895 Unique values: [1 2 3 4] Count of respective unique values: [1 1 1 1]
Transformation Operations on NumPy arrays
Various operations can be performed to transform the shape and order of elements in a NumPy array.
Operations | Built-In NumPy Functions |
Change the shape of an array | numpy.array.reshape() |
Sort the elements of an array | numpy.sort() |
Change n-d array to 1-D array | numpy.array.flatten() |
Transpose an array | numpy.array.transpose() |
import numpy as np # Creating a 1-D numpy array arr = np.array([6, 5, 4, 3, 2, 1]) # Print the array print("arr:\n", arr) print("Shape of arr: ", arr.shape) print("\n") # Sort the array in ascending order print("Sorted array: ", np.sort(arr)) print("\n") # Change the array shape to (2, 3) reshaped_arr = arr.reshape(2, 3) print("Reshaped array: ", reshaped_arr) print("Shape of reshaped array: ", reshaped_arr.shape) print("\n") # Transform the reshaped array transposed_arr = reshaped_arr.transpose() print("Transopose array: ", transposed_arr) print("Shape of transposed array: ", transposed_arr.shape) print("\n") # Change the reshaped array (which is 2-D) to 1-D flattened_arr = reshaped_arr.flatten() print("Flattened array: ", flattened_arr)
arr: [6 5 4 3 2 1] Shape of arr: (6,) Sorted array: [1 2 3 4 5 6] Reshaped array: [[6 5 4] [3 2 1]] Shape of reshaped array: (2, 3) Transopose array: [[6 3] [5 2] [4 1]] Shape of transposed array: (3, 2) Flattened array: [6 5 4 3 2 1]
This is it for operations on NumPy arrays. Head on to the next chapter to learn about ‘Input/Output operations in NumPy‘.