Numpy is a python library to create homogeneous multidimensional arrays and provide tools for working with these arrays.
The elements of numpy array are of the same type. One can create an array in Python using lists or array() function. The advantage of using Numpy array is it scales better and takes less memory when compared to standard Python list or array.
Using Numpy, you can perform following operations:
- Mathematical and logical operations on arrays.
- Fourier transforms and routines for shape manipulation.
- Operations related to linear algebra. NumPy has inbuilt functions for linear algebra and random number generation.
- NumPy Arrays: A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers.
- Rank: The number of dimensions is the rank of the array.
- Shape: the shape of an array is a tuple of integers giving the size of the array along each dimension.
Question: Give Rank for the following NumPy arrays:
1) [1, 2, 1]
2) [[ 1., 2., 3.],
[ 3., 0., 2.]]
The first array has rank 1 because the array is one dimensional. Second numpy array has rank 2 because it is a two-dimensional array.
Installation – NumPy
There are many ways to install Numpy library. Here is the link to official documentation to do so.
The simplest way to install Numpy is to write this in your command line.
pip install numpy
Ndarray and Ndarray Attributes
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality. Here is some most important attribute of the ndarray object:
- ndarray.ndim: the number of dimensions of the array. In Numpy, the number of dimensions is also the rank of the array.
- ndarray.shape: A tuple of integers representing the size of an array. For a matrix with n rows and m columns, the shape will be (n,m).
- ndarray.size: the total number of elements of the array. It is also equal to the product of the elements of shape.
- ndarray.dtype: It is an object that describes the type of the elements in the array.
- ndarray.data: It is a buffer that contains the actual elements of the array.
import numpy as np a = np.array([1, 2, 3]) # Create a rank 1 array print(type(a)) # Prints "<class 'numpy.ndarray'>" print(a.shape) # Prints "(3,)" print(a, a, a) # Prints "1 2 3" a = 5 # Change an element of the array print(a) # Prints "[5, 2, 3]" print(a.size) b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array print(b.shape) # Prints "(2, 3)" print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"\ print(a.ndim)
Here are the links to tutorials to get started with basics of Python.