-
What is NumPy
NumPy (short for Numerical Python) provides an efficient interface to store and operate on dense data buffers.
It is similar to Python’s built-in list type, but NumPy arrays provide much more efficient storage and data operations as the arrays grow larger in size.NumPy is used to work with arrays. The array object in NumPy is called
ndarray
Creating NumPy arrayLet’s create one dimensional array of NumPyimport numpy as npy = np.array([1, 2, 3, 4, 5, 6])NumPy array attributesndim, shape, size are attributes of the arrayprint(“y ndim: “, y.ndim)
print(“y shape:”, y.shape)
print(“y size: “, y.size)y ndim: 1y shape: (6,)y size: 6Array Indexing
In a one-dimensional array, you can access the nth value (counting from zero) by specifying the desired index in square brackets
Example:
The index starts from 0, so the first element of the array is accessed using y[0]
y[3] outputs 4To index from the end of the array, you can use negative indices
y[-2] outputs outputs 5
Array Slicing
The NumPy slicing syntax follows that of the standard Python list;
To access a slice of an array y, use this:
y[start:stop:step]import numpy as npy = np.array([0,1, 2, 3, 4, 5, 6,7,8,9,10])y[:5] # first five elementsy[5:] # elements after index 5Array Concatenation
Concatenation, or joining of two arrays in NumPy, is primarily accomplished through the routines np.concatenate.
np.concatenate takes a tuple or list of arrays as its first argument.Example
x = np.array([1, 2, 3, 4])
y = np.array([4, 3, 2, 1])
np.concatenate([x, y])array([1, 2, 3, 4, 4, 3, 2, 1])
Splitting of arrays
The opposite of concatenation is splitting, which is implemented by the function np.split
we can pass a list of indices giving the split points:
Example
y = [1, 2, 3, 55, 55, 3, 2, 1]y1, y2, y3 = np.split(y, [3, 5]) # The array is to be split starting index 3 until index 5print(y1, y2, y3)[1 2 3] [55 55] [3 2 1]NumPy uFunctions
NumPy has a few universal functions, which are useful in various computations.
Suming the values
import numpy as np
y = np.array([1, 2, 3, 4, 5, 6])
np.sum(y)
21Min , Max and Meannp.min(y)1np.max(y)
6np.mean(y)3.5Variancenp.var(y)
2.9166666666666665Standard deviationnp.std(y)
1.707825127659933