Understanding Numpy With Examples

Whenever you have started with DataScience Project or even Data Analytics project you might have come across the term Numpy, or you might be about to start to learn Data Science or Data Analytics. So first let us understand Numpy beginning with the definition, followed by examples and also understanding those examples.

What is Numpy? 

Numpy stands for Numerical Python, it is one of the scientific package libraries in the Python programming language that provides supports for multidimensional arrays also with fast operations on arrays. Numpy has a fixed size array creation with core as ndarray object facilitating advanced mathematical and other large numbers of data.


If you use windows use the following command for pip installation.

pip install numpy

or if you use conda, you can install from conda forge or from defaults as follows,

# Use an environment rather than install in the base env
conda create -n my-env
conda activate my-env
# If you want to install from conda-forge
conda config --env --add channels conda-forge
# The actual install command
conda install numpy

Now when you have a clean installation completed you can start your practice. Numpy provides high-performance multidimensional array objects and tools to work with the arrays. The elements in Numpy arrays are accessed by square brackets and can be initialized by nested Python Lists. The array type can be explicitly defined while creation of the array.

# Python program for creation of Arrays
import numpy as np
# Creating a rank 1 Array
array1 = np.array([5, 7, 8])
print("Array with Rank 1: \n",array1)
# Creating a rank 2 Array
array2 = np.array([[10, 50, 30],
                [20, 40, 60]])
print("Array with Rank 2: \n", array2)
# Creating an array from tuple
array3 = np.array((23, 84, 28))
print("Array created using passed tuple:\n", array3)

Creation of array using ndmin where it implies a minimum dimension of the resultant array.

import numpy as np 
a = np.array([15, 55, 35,45,90], ndmin = 2) 
print a

The next will be the creation of an array using dtype parameter which implies the creation of an array with the desired data type.

# dtype parameter 
import numpy as np 
a = np.array([25, 32, 87], dtype = complex) 
print a

The .shape returns the attribute of array dimension also can resize according to purpose.

import numpy as np 
a = np.array([[55,65,75],[25,35,45]]) 
print a.shape

also to resize the same.

import numpy as np 

a = np.array([[55,65,75],[25,35,45]]) 
a.shape = (3,2) 
print a 

The .ones can be used to create an array of specified size and type, filled with ones, for example,

import numpy as np 
x = np.ones(10) 
print x

Hopefully, you have understood the above operations on Numpy, please note that there are more and with a good amount of practice with invested time and understanding one can have a good grip and depth of the knowledge of Numpy, till then happy coding.

Similar Articles