NumPy is a Python library that provides fast and efficient operations on large multi-dimensional arrays. NumPy is the fundamental package for scientific computing in Python.
Installation
Install NumPy using conda:
condainstallnumpy
Install NumPy using pip:
pipinstallnumpy
Import NumPy
To use NumPy, import the numpy module:
import numpy as np
NumPy Arrays
NumPy arrays are multi-dimensional arrays. NumPy arrays are created using the numpy.array() function.
Create a NumPy array:
import numpy as nparr = np.array([1, 2, 3, 4, 5])print(arr)
There are several other commonly used functions to create NumPy arrays:
import numpy as np# Create an array of zerosarr = np.zeros((2, 3))print(arr)# Create an array of onesarr = np.ones((2, 3))print(arr)# Create an array using a rangearr = np.arange(1, 10, 2)print(arr)# Create an array using a range and reshapearr = np.arange(12).reshape(3, 4)print(arr)
In the last example, np.arange(12) creates an array of integers from 0 to 11. reshape(3, 4) reshapes the array to a 3x4 matrix. The resulting array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
NumPy Array Attributes
NumPy arrays have several attributes that provide information about the array.
np.concatenate() function concatenates arrays along a specified axis. The arrays must have the same shape, except in the dimension corresponding to the axis.
np.split() function splits an array into multiple sub-arrays.
Consider the following matrix:
04815926103711
import numpy as npa = np.arange(12).reshape(3, 4)# split a into 2 sub-arrays along the axis=1print(np.split(a, 2, axis=1))'# split a into 3 sub-arrays along the axis=0print(np.split(a, 3, axis=0))a = np.array([1, 2, 3, 4, 5, 6])print(np.split(a, [2, 3]))# [array([1, 2]), array([3]), array([4, 5, 6])]
If the second parameter is an array of sorted integers, the array is split at the indices specified by the integers. For example, np.split(a, [2, 3]) splits the array as
After changing the value of x, the value of y is also changed because y is a reference to x. The value of z remains unchanged because z is a copy of x.
It is important to note that np.copy() is a shallow copy. It will not copy objects within the array.