NumPy Array Tutorial – Python NumPy Array Operations and Methods
Free NumPy course with real-time projects Start Now!!
The most important feature of NumPy is the homogeneous high-performance n-dimensional array object. Data manipulation in Python is nearly equivalent to the manipulation of NumPy arrays.
NumPy array manipulation is basically related to accessing data and sub-arrays. It also includes array splitting, reshaping, and joining of arrays. Even the other external libraries in Python relate to NumPy arrays.
Numpy Array Basics
Arrays in NumPy are synonymous with lists in Python with a homogenous nature. The homogeneity helps to perform smoother mathematical operations.
These arrays are mutable. NumPy is useful to perform basic operations like finding the dimensions, the bite-size, and also the data types of elements of the array.
NumPy Array Creation
1. Using the NumPy functions
NumPy has a variety of built-in functions to create an array.
a. Creating one-dimensional array in NumPy
For 1-D arrays the most common function is np.arange(..), passing any value create an array from 0 to that number.
import numpy as np array=np.arange(20) array
Output
We can check the dimensions by using array.shape.
Output
To access the element of the array we can specify its non-negative index.
array[3]
Output
b. Creating two-dimensional arrays in NumPy
We can use reshape()function along with the arange() function to create a 2D array. The reshape()function specifies the rows and columns.
array=np.arange(20).reshape(4,5)
Output
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]])
In 2-D arrays to access the elements, we will require to specify two values for row and column respectively.
Similarly, we can create 3-D and more by increasing the number of parameters in the reshape()function.
c. Using other NumPy functions
We can use other functions like and to quickly create filled arrays.
np.zeros((2,4)) np.ones((3,6))
Output
[0., 0., 0., 0.]])array([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.]])
The .empty() function creates an array with random variables and the full() function creates an n*n array with the given value.
np.empty((2,3)) np.full((2,2), 3)
Output
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
array([[3, 3],
[3, 3]])
The .eye( , )function creates an array with diagonals as 1 and other
values as 0. The .linspace(, ,)
function outputs an equally spaced array.
np.eye(3,3) np.linspace(0, 10, num=4)
Output
[0., 1., 0.],
[0., 0., 1.]])
array([ 0. , 3.33333333, 6.66666667, 10. ])
Sr No. | Function | Description |
1 | empty_like() | Return a new array with the same shape and type |
2 | ones_like() | Return an array of ones with the same shape and type. |
3 | zeros_like() | Return an array of zeros with the same shape and type |
4 | full_like() | Return a full array with the same shape and type |
5 | asarray() | Convert the input to an array. |
6 | geomspace() | Return evenly spaced numbers on a log scale. |
7 | copy() | Returns a copy of the given object |
8 | diag() | a diagonal array |
9 | frombuffer() | buffer as a 1-D array |
10 | fromfile() | Construct an array from text or binary file |
11 | bmat() | Build a matrix object from a string, nested sequence, or array |
12 | mat() | Interpret the input as a matrix |
13 | vander() | Generate a Vandermonde matrix |
14 | triu() | Upper triangle of array |
15 | tril() | Lower triangle of array |
16 | tri() | An array with ones at & below the given diagonal and zeros elsewhere |
17 | diagflat() | two-dimensional array with the flattened input as a diagonal |
18 | fromfunction() | executing a function over each coordinate |
19 | logspace() | Return numbers spaced evenly on a log scale |
20 | meshgrid() | Return coordinate matrices from coordinate vectors |
2. Conversion from Python structure like lists
We can use the Python lists to create arrays by passing a list to the array function. We can also directly create an array of elements by passing a list.
array=np.array([4,5,6]) array list=[4,5,6] list
Output
array([4, 5, 6])[4, 5, 6]
To create 2-D or more we pass a sequence of lists.
3. Using other library functions
We can use the function to create an array with random values between 0 and 1. This is a useful case in scenarios with random nature.
np.random.random((2,3))
Output
[0.3754818 , 0.63166016, 0.5901392 ]])
NumPy Array Indexing
Indexing of the array has to be proper in order to access and manipulate its values. Indexing can be done through:
- Slicing – we perform slicing on NumPy arrays with the declaration of a slice for all the dimensions.
- Integer array Indexing– users can pass lists for one to one mapping of corresponding elements for each dimension.
- Boolean Array Indexing– we can pick elements after satisfying a particular Boolean condition.
NumPy Basic Array Operations
There is a vast range of built-in operations that we can perform on these arrays.
1. ndim – It returns the dimensions of the array.
2. itemsize – It calculates the byte size of each element.
3. dtype – It can determine the data type of the element.
4. reshape – It provides a new view.
5. slicing – It extracts a particular set of elements.
6. linspace – Returns evenly spaced elements.
7. max/min , sum, sqrt
8. ravel – It converts the array into a single line.
There are also a few Special Operations like sine, cosine, tan, log, etc.
Checking Array Dimensions in NumPy
We can determine the NumPy array dimensions using the ndim attribute. The argument return an integer that indicates the array dimension.
import numpy as np a = np.array(10) b = np.array([1,1,1,1]) c = np.array([[1, 1, 1], [2,2,2]]) d = np.array([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) print(a.ndim) print(b.ndim) print(c.ndim) print(d.ndim)
Output
Higher Dimensional Arrays in NumPy
In Numpy we can have arrays with any number of dimensions. There can be arrays with a high number of dimensions. We define the number of dimensions with the ndim argument.
import numpy as np arr = np.array([1, 1, 1, 1, 1], ndmin=10) print(arr) print('number of dimensions :', arr.ndim)
Output
In the above example, the innermost dimension (10th dim) has 5 elements, the 9th dim has 1 element that is the vector, the 8th dim has 1 element that is the matrix with the vector, the 7th dim has 1 element that is 3D array 6th dim has 1 element that is a 4D array and so on.
Indexing and Slicing in NumPy
These are two very important concepts. It is useful when we want to work with sub-arrays.
Indexing starts with zero as the first index. We can retrieve element values by its index value. For 2 or more dimensional arrays, we have to specify 2 or more indices. Indexing can be of two types
1. Integer array indexing
We pass lists for indexing in all the dimensions. Then one to one mapping occurs for the creation of a new array.
2. Boolean array indexing
In this type of indexing, we carry out a condition check. If the boolean condition satisfies we create an array of those elements.
import numpy as np arr=([1,2,5,6,7]) arr[3]
Output
Slicing is similar to indexing, but it retrieves a string of values. The range is defined by the starting and ending indices. It is similar to lists in Python. The arrays can also be sliced. The arrays can be single or multidimensional. We can specify slices for all the dimensions.
import numpy as np arr=([1,2,5,6,7]) arr[2:5]
Output
Advanced Methods on Arrays in NumPy
A few advanced methods available for NumPy Arrays are -:
1. Staking (along different axes) – Horizontally, Vertically, as columns and we can also perform concatenation along a specific axis.
2. Splitting – Array can be split along horizontal, vertical, or along a specific axis.
3. Broadcasting – with this method we can convert arrays to have compatible shapes to perform arithmetic operations. In order to broadcast the trailing axes should be either the same or one of them should be one.
4. DateTime – NumPy has its own DateTime data type like python’s inbuilt named datetime64.
5. Linear algebra – we can perform linear algebra on arrays using this module.
Summary
A vast range of operations is available for NumPy array manipulation. We can start operating with arrays using these basic tools of array creation, indexing, etc.
Creating and populating the array with elements is the most basic function. Above is more of a brief introduction to the available function and methods on arrays.
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google