In this short guide, you’ll see how to get started with NumPy.
First, install NumPy using the command:
pip install numpy
Import numpy as np
To use the NumpPy package, you’ll need to type “import numpy as np” at the top of your code.
You’ll then be able to use NumPy functions and objects by prefixing them with np., like np.array() to create a NumPy array.
Here’s an example that demonstrates how to “import numpy as np” and then use it to create a simple 1D NumPy array:
import numpy as np # Create a 1D NumPy array arr = np.array([1, 2, 3, 4, 5]) # Print the array print(arr)
The resulted 1D array:
[1 2 3 4 5]
Here is an example of 2D NumPy array:
import numpy as np # Create a 2D NumPy array arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Print the array print(arr)
The resulted 2D array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Calculate the sum of each column
To calculate the sum of each column (axis=0) using np.sum():
import numpy as np # Create a 2D NumPy array arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Calculate the sum of each column col_sum = np.sum(arr, axis=0) print(col_sum)
The result:
[12 15 18]
Where the calculation of the sum of each column goes as follows:
- 12 = 1 + 4 + 7
- 15 = 2 + 5 + 8
- 18 = 3 + 6 + 9
Calculate the mean of each row
To calculate the mean of each row (axis=1) using np.mean():
import numpy as np # Create a 2D NumPy array arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Calculate the mean of each row row_mean = np.mean(arr, axis=1) print(row_mean)
The result:
[2. 5. 8.]
Where the calculation of the mean of each row is:
- 2 = (1 + 2 + 3) / 3
- 5 = (4 + 5 + 6) / 3
- 8 = (7 + 8 + 9) / 3