Basic of Python — Numpy

Nitish Srivastava
5 min readMay 11, 2022

--

NumPy (Numerical Python) is an open source Python library that’s used to solve different kind of scientific and numerical problems. The NumPy library contains multidimensional array and matrix data structures. It provides homogeneous n-dimensional array (ndarray) object, with methods to efficiently operate on it. It can used to solve variety of mathematical and statistical operations on arrays.

How to install Numpy?

1. In anaconda environment — conda install numpy

2. In pip environment — pip install numpy

How to import Numpy in your project modules?

Import numpy as np

To access numpy function we can use above statement in our modules and we can also provide a short name to access it, like here I have used np.

What is alias or Short naming for library?

This is the way you can give an short alias for existing library, like import pandas as pd, for panda, or import mycustomlibrarylongnameexample as mylb, and call just mylb.and_your_function_or_object_name.

Let’s an example of numpy array and understand difference between numpy array and normal python list.

# ====== create range array ==================

//Example of Range

ar = range(6)

# Output — range(0,6)

list(ar)

# Output — [0,1,2,3,4,5]

// Example of Numpy

ar = np.arange(6) # Output — array[0,1,2,3,4,5]

Just execute above code in terminal and see output. Try more, different variables, different array size and different values.

Why Numpy based maniplulation is better than normal python list?

Let’s see an example to add values in the list/array. Write below given code on your python terminal and test.

import time

import numpy as np

print(==== Example for range =====”)

start = time.time()

total_sum = sum(range(100000000))

print(“Result — Duration: {total_sum} — {time.time() — start} seconds”)

print(“===== Example for numpy =====”)

start = time.time()

total_sum = np.sum(np.arange(100000000))

print(“Result — Duration: {total_sum} — {time.time() — start} seconds”)

You can see output like this,

==== Example for range =====

Result — Duration: 4999999950000000–1.1205904483795166 seconds

===== Example for numpy =====

Result — Duration: 4999999950000000–0.7411048412322998 seconds // it may be different, but yes, duration value will be less than range one.

In above output, you can see numpy tooks less time than range to sum array of 0 to 100000000. It’s a small example. You can try more.

Few another examples :-

Convert one dimensional array into multidimensional

So, first question maybe you are thinking, what is an array? I think everyone has already studied about it on their school, while studying, C or C++. An array is a grid of values. It can be one dimensional, two dimensional or N-dimensional. Basically, in array all elements are same type, called dtype.

Example — A= [1,2,3,4,5,6] //An array with length 6

Every element in an array is exists on an index started from 0. like above example 1 is on 0 index of array a. So last index = length of array -1

A[0] = 1

A[1] = 2

A[2] = 3

A[3] = 4

A[4] = 5

A[5] = 6

In python, a list is an array. Here A is list. You can convert a list into NumPy array by np.array(A) (np is alias for NumPy).

Convert a one-dimensional array into multidimensional

To convert a one-dimensional array to multidimensional, you can use reshape function.

Like,

A = np.array([1,2,3,4,5,6])

Here, A contains 6 elements. You can only convert an array into multidimensional based on its size. Like,

A = [1,2,3,4,5,6]

A.reashape(1,6) //output:- array([[1, 2, 3, 4, 5, 6]]) — two dimensional

A.reshape(1,6,10) //output:- array([[[1],[2],[3],[4],[5],[6]]]) — three dimensional

A.reshape(1,6,1,1) //output:- array([[[[1],[2],[3],[4],[5],[6]]]])

Inside reshape, whatever nos of parameter you are passing, will create that size of array.

Another example,

A.reshape(2,3) //output array([[1, 2, 3], [4, 5, 6]])

In above example, you are creating one two-dimensional array, where second array size will be 2 and each array will contain 3 elements.

A.reshape(2,3,1) //output array([[1], [2], [3], [4,] [5], [6]])

n above example, you are saying that A is a three-dimensional array, where main array contains 2 another array, and inside array contains another 3 array and each array contains 1 element.

Mean, last one is always elements. And other first value is saying, main array contains, inner some array and same for next.

Some basic other manipulations in numpy.

A = np.array([1,2,5,6,4,3])

B = np.array([1,2,3,4,5,6])

Sort array in ascending order :- np.sort(A)

Sort array in descending order :- -np.sort(-A), or np.sort(A)[::-1]

Sum array’s elements :- np.sum(A) //return 21 integer value

Sum two array :- np.add(A,B)

Concatinate two arrays :- np.concatenate((A,B), axis=0) // join two array in one

Know shape of array :- A.shape — Output :- (6,)

Dimension of array :- A.ndim — Output :- 1

Size of array :- A.size — Output :- 6

Lets Try these three on another dimension :-

A = np.array([[1, 2, 3], [4, 5, 6]])

Know shape of array :- A.shape — Output :- (2, 3)

Dimension of array :- A.ndim — Output :- 2

Size of array :- A.size — Output :- 6

Convert multidimensional to one dimensional -

A.flatten() //Output :- array([1, 2, 3, 4, 5, 6])

A.ravel() //Output :- array([1, 2, 3, 4, 5, 6])

Save NumPy object in a disk file as .npy extension, so you can transfer your NumPy object one place to another and read again.

np.save(“filename”, A)

It will save file on your disk. You can read this object using load function.

Example:-

A = np.array([1,2,3,4,5,6])

np.save(“test”, A)

B = np.load(“test.npy”)

So, output of B is array([1,2,3,4,5,6]). Do like this, save your file in your computer and open this file in your friend computer. Writing object to file called serialization and converting file to object called deserialization.

Let’s an another example to convert an image into NumPy array and then NumPy array to image:

# Image to numpy array

from PIL import Image

image = Image.open(“image.png”)

image_array = np.array(image)

#numpy array to image

Image.fromarray(image_array).save(“image.png”)

If you will be master on it, you can create your own image using numpy array.

Check, what is np.ones, np.zeros, np.empty, np.tan, np.sin, np.cos, np.add, np.subtract, np.multiply, np.divide, np.percentile, np.copy etc.

Also try, dir and help function with different numPy functions. Like help(np.sort), dir(np) etc.

There is so many things, NumPy contains. Not possible to teach in one article. Its just for your idea. Give your time to study about NumPy from different websites like, tutorials point, numpy.org, search articles based on NumPy.

(Sorry for grammatical mistakes)

--

--

Nitish Srivastava
Nitish Srivastava

Written by Nitish Srivastava

Full stack developer, with experience in Java, Spring, Python, Angular, Android, Ionic, Flutter, Blockchain NFT and Cryptocurrency

No responses yet