Numpy

NumPy is a Python library used for working with arrays. It also has functions for working in domain of linear algebra, fourier transform, and matrices. In Python we have lists that serve the purpose of arrays, but they are slow to process.

Why Numpy Array Is better

NumPy aims to provide an array object that is up to 50x faster than traditional Python lists. The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working with ndarray very easy. Arrays are very frequently used in data science, where speed and resources are very important.NumPy is a Python library and is written partially in Python, but most of the parts that require fast computation are written in C or C++.

Installation Of Numpy Using pip

To install numpy we can either run

pip install numpy in your command prompt or terminal or

!pip install numpy in a your jupyter notebook code cell

!pip install numpy
Requirement already satisfied: numpy in /home/manu/.local/lib/python3.8/site-packages (1.19.4)

Importing Numpy

import numpy as np
# np is a very common alias name of numpy module

Intialization Of Numpy Array

# One Dimensional Array
a = np.array([1, 2, 3, 4, 5, 6])

#Two Dimensional Array
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Printing the Array 
print(a)
print("----------------")
print(b)
print("----------------")
# We can use indexing for printing any specific element of the array
print(a[0])
print("----------------")
print(b[0][2])
print("----------------")
# In case of 2d array providing one index will access the 1d array present at that index
print(b[0])
[1 2 3 4 5 6]
----------------
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
----------------
1
----------------
3
----------------
[1 2 3 4]
l=[1,2,3,4,5,] #Python List

array=np.array(l) #providing any python list will do exactly the same as above.
print(array)

# We can also provide data type at the time of declaring
floatArray=np.array(l,dtype=np.float32)
print("----------------")
print(floatArray)
print(type(floatArray[0]))
[1 2 3 4 5]
----------------
[1. 2. 3. 4. 5.]
<class 'numpy.float32'>

np.arrange() method takes a Lower limit,upper limit ,and step and Create a Array with starting element as lower limit and last element less than the given upper limit incrrasing values by given step Upper element is Exclusive

np.arange([start, ]stop, [step, ]dtype=None, *, like=None)

arr= np.arange(2,10,2,dtype=np.int32)
print(arr)
[2 4 6 8]

Some Data Type In Numpy

  1. np.int32

  2. np.int64

  3. np.float32

  4. np.float64

Arrays of Zeros or Ones

Generating numpy array with all zeros

np.zeros(shape, dtype=float, order='C', *, like=None)

Zeros=np.zeros((2,3),dtype=np.float32)
print(Zeros)
[[0. 0. 0.]
 [0. 0. 0.]]

Generating numpy array with all ones

np.zeros(shape, dtype=float, order='C', *, like=None)

Ones=np.ones((3,2))
print(Ones)
[[1. 1.]
 [1. 1.]
 [1. 1.]]

Shape, Size and Dimension

NumpyArray.shape tells the shape of the Array

NumpyArray.size tells the total number of element in the array

NumpyArray.ndim tells the number of dimension in the array

print(a.shape,b.shape)
print("----------------")
print(a.size,b.size)
print("----------------")
print(a.ndim,b.ndim)
(6,) (3, 4)
----------------
6 12
----------------
1 2

Reshaping

NumpyArray.reshape() Takes The new Shape Of The Array as Argument and Returns The New numpy Array

c=a.reshape(3,2)
print(c)
print("----------------")
print(c.shape)
[[1 2]
 [3 4]
 [5 6]]
----------------
(3, 2)

Giving -1 As one of the argument means to identify the that value itself

Only one such Dimension can be Given

c=a.reshape(-1,2)
print(c)
print("----------------")
print(c.shape)
[[1 2]
 [3 4]
 [5 6]]
----------------
(3, 2)

Adding And Removing Element

Addition

value = 9

index = 1

Insertion at first index

This Methods Returns a new Numpy Array

# Addition 
print(array)
print("----------------")
newArray=np.insert(array,1,6)
print(newArray)
[1 2 3 4 5]
----------------
[1 6 2 3 4 5]

Deletion

Takes Two Argument array and index of the element to be deleted

This Methods Returns a new Numpy Array

# Deletion of the element in the Array
print(array)
print("----------------")
newArray=np.delete(array,1)
print(newArray)
[1 2 3 4 5]
----------------
[1 3 4 5]

Slicing And Indexing

we can slice the index in numpy when accessing elements using slicing operation

NumpyArray[start:end:step]

print(arr)
print("----------------")
print(arr[1:3])# last index value in excluded
[2 4 6 8]
----------------
[4 6]

In case of 2d Array

print(c)
print("----------------")
print(c[1:3,0:2])#excessing a 2d array's all row from 1 to 2 and 0 to 2 column
print("----------------")
print(c[1:3][1])#from array havimg row 1 to 2 accessing 0th column
[[1 2]
 [3 4]
 [5 6]]
----------------
[[3 4]
 [5 6]]
----------------
[5 6]

Using Negative indexes

In numpy Negative index can also be used to access the element -1 indicating the last index -2 indicating the second last and so on…

print(arr)
print("----------------")
print(arr[-1])
print("----------------")
print(arr[-1:-3:-1])
[2 4 6 8]
----------------
8
----------------
[8 6]

Some Utility Functions

Sum

np.sum(NumpyArray,axis=None, dtype=None) specifying axis tells the direction along which the operation is to be done

If Nothing given sum of every element in the array is given as output

print(c)
print("----------------")
totalSum=np.sum(c)
print(totalSum)
print("----------------")
xsum=np.sum(c,axis=1)
print(xsum)
print("----------------")
ysum=np.sum(c,axis=0)
print(ysum)
[[1 2]
 [3 4]
 [5 6]]
----------------
21
----------------
[ 3  7 11]
----------------
[ 9 12]

Mean

np.mean(NumpyArray,axis=None, dtype=None) specifying axis tells the direction along which the operation is to be done

If Nothing given sum of every element in the array is given as output

print(c)
print("----------------")
totalMean=np.mean(c)
print(totalMean)
print("----------------")
xmean=np.mean(c,axis=1)
print(xmean)
print("----------------")
ymean=np.mean(c,axis=0)
print(ymean)
[[1 2]
 [3 4]
 [5 6]]
----------------
3.5
----------------
[1.5 3.5 5.5]
----------------
[3. 4.]

Max

max operation in the numpy returns the maximum value present in the array NumpyArray.max(axis=None) specifying axis tells the direction along which the operation is to be done

If Nothing given sum of every element in the array is given as output

print(c)
print("----------------")
maxval=c.max()
print(maxval)
print("----------------")
xmax=c.max(axis=1)
print(xmax)
print("----------------")
ymax=c.max(axis=0)
print(ymax)
[[1 2]
 [3 4]
 [5 6]]
----------------
6
----------------
[2 4 6]
----------------
[5 6]

Argmax

argmax operation returns the first index of the maximum element in the numpy array np.argmax(a, axis=None) specifying axis tells the direction along which the operation is to be done

If Nothing given sum of every element in the array is given as output

print(c)
print("----------------")
maxval=np.argmax(c)
print(maxval)
print("----------------")
xmax=np.argmax(c,axis=1)
print(xmax)
print("----------------")
ymax=np.argmax(c,axis=0)
print(ymax)
[[1 2]
 [3 4]
 [5 6]]
----------------
5
----------------
[1 1 1]
----------------
[2 2]

Operations on Numpy Array

In case of a numpy array any mathematical operations work directly on every element of the array. making very useful when performing any vector like calculations

In below mentioned example 2 got added to every element of the array and in next one every element got divided by 2

print(a)
new_a=a+2
print("----------------")
print(new_a)
[1 2 3 4 5 6]
----------------
[3 4 5 6 7 8]
print(a)
new_a2=a/2
print("----------------")
print(new_a2)
[1 2 3 4 5 6]
----------------
[0.5 1.  1.5 2.  2.5 3. ]

This element-wise opeartions also work in the case of multi-dimension numpy array and between two numpy array operation specified will happen between every elements of the array specified

print(a,new_a)
print("----------------")
new_a=a+new_a
print(new_a)
print("----------------")
multiplied_a=new_a*a
print(multiplied_a)
[1 2 3 4 5 6] [3 4 5 6 7 8]
----------------
[ 4  6  8 10 12 14]
----------------
[ 4 12 24 40 60 84]

For element wise opeartion to happen dimension and size is very important factor

arr=np.arange(5)
print(a,len(a))
print("----------------")
print(arr,len(arr))
[1 2 3 4 5 6] 6
----------------
[0 1 2 3 4] 5

As, size of a and arr are not equal, element wise operation will not occur here and it will give ValueError. Same thing also occur for any dimensions array. It follows the rule of broadcasting brief explanation can be found in the official documentation

print(a+arr)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-76f384bd1f35> in <module>
----> 1 print(a+arr)

ValueError: operands could not be broadcast together with shapes (6,) (5,) 

As seen above due to diffrent sizes it was unable to broadcast and thus throwed error

Further Readings