NumPy, which stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. Using NumPy, mathematical and logical operations on arrays can be performed.
Features of NumPy :
Numpy library is the core library for scientific computing in python.It can perform the following
Mathematical and logical operations on arrays.
Fourier transforms and routines for shape manipulation.
Operations related to linear algebra. NumPy has in-built functions for linear algebra and random number generation.
A NumPy array is a multidimensional array of the same type of objects.
It is an object which points to a block of memory.
It is able to track the type of data stored in the memory,number of dimensions,size of the dimensions.
Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.
Let us see the benefits of numpy using reshape example .
Reshaping NumPy Array
Using NumPy you can convert a one-dimensional array into a two-dimensional array with the reshape method.
The following code can change one dimensional array to specified order of array.Here the first array is converted to 5*2 and second array is converted to order of 2*2 in the output.Also it will show the time taken to execute the code.
import numpy as np import timeit start = timeit.default_timer() np_md_arr = np.array([[1,2,3,4,5],[6,7,8,9,10]]) np_modmd_arr = np_md_arr.reshape(5,2) np_md_arr2 = np.array ([1,2,3,4]) np_modmd_arr2 = np_md_arr2.reshape(2,2) print (np_modmd_arr) print(np_modmd_arr2) stop = timeit.default_timer() execution_time = stop - start print("Program Executed in seconds "+str(execution_time))
Output of the above code:
[[ 1 2] [ 3 4] [ 5 6] [ 7 8] [ 9 10]] [[1 2] [3 4]] Program Executed in seconds 0.0025862229999802366
The code with python lists for the same output takes longer than above to get executed.
It is pertinent to mention that you cannot reshape an array if the number of elements in the one-dimensional array is not equal to the product of rows and columns of the reshaped array. For instance, if you have 45 elements in a 1-d array, you cannot reshape it into a matrix of 5 row and 10 columns since a 5*10 matrix has 50 elements and the original one only has 45.
Hence,Numpy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons built in sequences.