Numpy
Numpy
Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of
positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of
integers giving the size of the array along each dimension is known as shape of the array. An array
class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets
and can be initialized by using nested Python Lists.
Example :
[[ 1, 2, 3],
[ 4, 2, 5]]
Python
import numpy as np
[4, 2, 5]])
Output
Size of array: 6
Array Creation
For example, you can create an array from a regular Python list or tuple using
the array function. The type of the resulting array is deduced from the type of the elements
in the sequences.
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy
offers several functions to create arrays with initial placeholder content. These minimize the
necessity of growing arrays, an expensive operation.
For example: np.zeros, np.ones, np.full, np.empty, etc.
To create sequences of numbers, NumPy provides a function analogous to range that returns
arrays instead of lists.
arange: returns evenly spaced values within a given interval. step size is specified.
linspace: returns evenly spaced values within a given interval. num no. of elements are
returned.
Reshaping array: We can use reshape method to reshape an array. Consider an array with
shape (a1, a2, a3, …, aN). We can reshape and convert it into another array with shape (b1,
b2, b3, …, bM). The only required condition is:
a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM . (i.e original size of array remains unchanged.)
Flatten array: We can use flatten method to get a copy of array collapsed into one
dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for
column major order.
Python
import numpy as np
b = np.array((1, 3, 2))
c = np.zeros((3, 4))
Output
Array Indexing
Knowing the basics of array indexing is important for analysing and manipulating the array object.
NumPy offers many ways to do array indexing.
Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array.
Integer array indexing: In this method, lists are passed for indexing for each dimension. One
to one mapping of corresponding elements is done to construct a new arbitrary array.
Boolean array indexing: This method is used when we want to pick elements from array
which satisfy some condition.
Python
# Python program to demonstrate
# indexing in numpy
import numpy as np
# An exemplar array
[2.6, 0, 7, 8],
# Slicing array
temp = arr[cond]
Output
[[-1. 0.]
[ 4. 6.]]
[4. 6. 0. 3.]
Basic operations
Python
import numpy as np
a = np.array([1, 2, 5, 3])
a *= 2
# transpose of array
print("\nOriginal array:\n", a)
Output
Unary operators: Many unary operations are provided as a method of ndarray class. This
includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by
setting an axis parameter.
Python
import numpy as np
[4, 7, 2],
[3, 1, 9]])
arr.max(axis=1))
arr.min(axis=0))
arr.sum())
arr.cumsum(axis=1))
Output
[[ 1 6 12]
[ 4 11 13]
[ 3 4 13]]
Binary operators: These operations apply on array elementwise and a new array is created.
You can use all basic arithmetic operators like +, -, /, , etc. In case of +=, -=, = operators, the
exsisting array is modified.
Python
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
# add arrays
print("Array sum:\n", a + b)
# matrix multiplication
Output
Array sum:
[[5 5]
[5 5]]
Array multiplication:
[[4 6]
[6 4]]
Matrix multiplication:
[[ 8 5]
[20 13]]
Universal functions (ufunc): NumPy provides familiar mathematical functions such as sin,
cos, exp, etc. These functions also operate elementwise on an array, producing an array as
output.
Note: All the operations we did above using overloaded operators can be done using ufuncs like
np.add, np.subtract, np.multiply, np.divide, np.sum, etc.
Python
import numpy as np
# exponential values
a = np.array([0, 1, 2, 3])
Output
Data Type
Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us
about the layout of the array. This means it gives us information about :
If the data type is a sub-array, what is its shape and data type.
The values of a ndarray are stored in a buffer which can be thought of as a contiguous block of
memory bytes. So how these bytes will be interpreted is given by the dtype object.
Every Numpy array is a table of elements (usually numbers), all of the same type, indexed by a tuple
of positive integers. Every ndarray has an associated data type (dtype) object.
This data type object (dtype) provides information about the layout of the array. The vaues of an
ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes which
can be interpreted by the dtype object. Numpy provides a large set of numeric datatypes that can be
used to construct arrays.
At the time of Array creation, Numpy tries to guess a datatype, but functions that construct arrays
usually also include an optional argument to explicitly specify the datatype.
Python
import numpy as np
print(np.dtype(np.int16))
Output
int16
Python
import numpy as np
# dt is a dtype object
dt = np.dtype('>i4')
Output
Size is: 4