Num Py
Numpy :- it is a pre defined library used in python to perform operations on array.
Num py array:- it is a collection of similar/homogenous type of elements
Eg :- [5 6 7 8]
[“a” “b” “c”]
Two types of array :-
One dimensional(vectors)
Two dimensional(matrices)
Difference between python list and numpy array
Python list Numpy array
It is a collection of similar or different type of It is a collection of similar type of elements
elements [1 2 3 4]
[1,12.5,”ABC”]
List elements are separated by , No separation is used between array elements
We can change size of list by append a value We cannot change size of an array
Acquire more space Acquire less space
Slower than array Faster than list
It does not support vectorized operation It support vectorized operation means if we
perform any operation on an array it will apply to
all items
Import np as array
X=np.array[1,2,3]
X=X+1
Print(x) //output [2 3 4]
Anatomy/terminologies of numpy arrays
1. Axes:- Dimension of array is known as axes starts with zero
For eg: 1-d array- axes-0, 2-d array- axes-1 ……
2. Rank:- Number of axes
For eg: 1-d array- rank-1, 2-d array- rank-2 ……
3. Shape/size: number of elements along each axis of it . Output in the form of tuple
Array Shape
[5 7 8] (3,)
[[5 7 8],[4 5 6]] (2,3) # ROW,COLS
[[5 7 8],[4 5 6],[1 2 3],[6 7 8]] (4,3)
Function used to calculate shape is shape
4. Item Size :- size of each elements in byte
Import numpy as np
X=np.array([5,7,8])
Print(x.itemsize) // output is 4
5. Datatype(dtype) : print the data type of values stored in array .
Note :- Data type of array is numpy.ndarray
Import numpy as np
X=np.array([5,7,8])
Print(x.dtype) // output is int32
-:Creating Numpy 1D Array:-
1. array():- create an array Using list
Import numpy as np // here numpy is represented as np
x=np.array([5,6,7,8]) // list is converted to array
print(x) // output [5 6 7 8]
2. fromiter() :-used to create non numeric sequence type array however it can create any type of
array(creating an array using dictionary or string values)
Import numpy as np // here numpy is represented as np
y={3:”d”,4:”e”,5:”f”}
x=np.fromiter(y,dtype=np.int32) // list is converted to array
print(x) // output [3 4 5]
Import numpy as np // here numpy is represented as np
y=”Hello”
x=np.fromiter(y,dtype=”U2”) // list is converted to array
print(x) // output [H e l l o]
Import numpy as np // here numpy is represented as np
y=”Hello”
x=np.fromiter(y,dtype=”U2”,count=3) // list is converted to array
print(x) // output [H e l] due to count only 3 values converted into array
3. arange() :- used to create an array using a sequence
syntax:
arange([start-value],end-value,[step],[dtype])
for eg :
Import numpy as np // here numpy is represented as np
x=np.arange (1,10,2,dtype=np.int32)
print(x) // output [1 3 5 7 9]
Import numpy as np // here numpy is represented as np
x=np.arange (1,10,2,dtype=np.float32)
print(x) // output [1. 3. 5. 7. 9.]
Import numpy as np // here numpy is represented as np
x=np.arange (3.4,10,2,dtype=np.float32)
print(x) // output [3.4 5.4 7.4 9.4]
4. linspace() :- this function is used to create equally spaced array
syntax:
linspace(start-value,end-value, number of values ,dtype)
Import numpy as np // here numpy is represented as np
x=np.linspace (3.5,10,3,dtype=np.float32)
print(x) // output [3.5 6.75 10.]
Import numpy as np // here numpy is represented as np
x=np.linspace (3.5,10,3,dtype=np.int32)
print(x) // output [3 6 10]
-:Creating Numpy 2D Array :-
1. array() :- create 2-d array using list
Import numpy as np
l1=[1,2,3]
l2=[4,5,6]
x=np.array([l1,l2])
print(x) // output [[1 2 3]
[4 5 6]]
2. arrange() :- crate 2-d array using a sequence , used with reshape function
Import numpy as np
x=np.arrange(6).reshape(2,3)
print(x) // output [[0 1 2]
[3 4 5]]
3. empty():- This function is used to create empty array of specified size and mentioned dtype.
Syntax:
empty(size of array,[dtype], [order])
order can be of two types:
“c”(contiguous order)- row major
“f”(fortran order)- colm major
Note By Default dtype is float32
Import numpy as np
x=np.empty([3,4],dtype=np.int32,order=”c”)
// it will create an array with 3 rows and 4 cols and filled with garbage values
4. zeros() :- This function is used to create empty array with zero values of specified size and mentioned
dtype.
zeros(size of array,[dtype], [order])
order can be of two types:
“c”(contiguous order)- row major
“f”(fortran order)- colm major
Import numpy as np
x=np.zeros([3,4],dtype=np.int32,order=”c”)
[ [0 0 0 0],
[0 0 0 0],
[0 0 0 0]]
5. ones () :- This function is used to create empty array with zero values of specified size and mentioned
dtype.
ones(size of array,[dtype], [order])
order can be of two types:
“c”(contiguous order)- row major
“f”(fortran order)- colm major
Import numpy as np
x=np.ones ([3,4],dtype=np.int32,order=”c”)
[ [1 1 1 1],
[1 1 1 1],
[1 1 1 1]]
6. zeros_like() :- creates an empty array same as size of already existing array with zero filled values
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
b=np.zeros_like(a)
print(a)
print(b) // [[0 0 0 ],
[0 0 0]]
7. ones_like():-:- creates an empty array same as size of already existing array with ones filled values
8. empty_like() :- creates an empty array same as size of already existing array
9. eye() :- create a 2-d square array(same no of rows and cols) with 1 on diagonal position and 0 at non
diagonal position
import numpy as np
a=np.eye(5)
// it will create a 5*5 array with 1 on diagonal position and 0 at non diagonal position
10. random.rand() Create a 2-d array and filled random float values between 0 to 1
import numpy as np
a=np.random.rand(3,4)
// it will create a 3*4 array filled with floating random values
import numpy as np
a=np.random.rand(3,4)*100
// it will create a 3*4 array filled with floating random values between 0 to 100
11. random.randint() Create a 2-d array and filled random float values between 0 to 1
random.randint(start,end,size)
import numpy as np
a=np.random.randint(1,10,size=(2,3))
// it will create a 3*4 array filled with floating random values between 1 to 10
Accessing Elements in 1-D Array :-
Import numpy as np // here numpy is represented as np
x=np.array([5,6,7,8]) // list is converted to array
print(x[1]) // output -6
Accessing Elements in 2-D Array :-
Import numpy as np
l1=[1,2,3]
l2=[4,5,6]
x=np.array([l1,l2])
print(x[1,2]) // output 6
Import numpy as np
l1=[1,2,3]
l2=[4,5,6]
x=np.array([l1,l2])
print(x[1,-2]) // output 5 negative indexing same as list
Modify Elements in 1-D/2-D Array :-
Import numpy as np
l1=[1,2,3]
l2=[4,5,6]
x=np.array([l1,l2])
x[1,2]=7 //value 6 is replaced by 7
Array Slicing 1-d array
Import numpy as np
x=np.array([1,2,3,4,5,6,7,8])
print(x[2:5]) // OUTPUT -3,4,5
print(x[:5]) // OUTPUT -1,2,3,4,5
print(x[2:]) // OUTPUT -3,4,5,6,7,8
print(x[:5:2]) // OUTPUT -1,3,5
print(x[1::2]) // OUTPUT -1,3,5,7
print(x[-6:-2]) // OUTPUT -3,4,5,6,7
Array Slicing 2-d array
Import numpy as np
x=np.array([5,6,6,7,8],[7,6,5,4,2],[5,6,4,3,2])
print(x[:2,2:] // output [ [6,7,8] [5,4,2]]
print(x[1::2,:3]) //output [[7,6,5]]
print(x[::3,::2]) //[5,6,8]
Concatenating Numpy array
1. hstack():- To concatenate two array horizontally. (Row Same Col m Add)
Concatenate two 1-d arrays
import numpy as np
a=np.array([1,2,3,4,5])
b=np.array([5,6,7,8,9])
c=np.hstack((a,b))
print(c)
Concatenate two 2-d arrays
Import numpy as np
x=np.array([5,6,6,7,8],[7,6,5,4,2]]
y=np.array([1,2,3,4,5],[6,7,8,9,9]]
z=np.hstack((x,y))
print(z)
output // first row on first two-d is concatenate with first row of first row of second two-d array and so on
[[5 6 6 7 8 1 2 3 4 5]
[7 6 5 4 2 6 7 8 9 9]]
2. vstack():- To concatenate two array vertically. (Colm Same row add)
Concatenate 1-d arrays
Import numpy as np
x=np.array(([5,6,6,7,8],[7,6,5,4,2],[5,6,4,3,2]))
print(x) // output [ [5 6 6 7 8] [7 6 5 4 2] [5 6 4 3 2]]
Concatenate two 2-d arrays
import numpy as np
ls1=[1,2,3]
ls2=[4,5,6]
ls3=[7,8,9]
ls4=[10,11,12]
x=np.array([ls1,ls2])
y=np.array([ls3,ls4])
a=np.vstack((x,y))
print(a)
output // first row on first two-d is concatenate with first row of first row of second two-d array and so on
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
3. concatenate():-
Axis-0 vstack()
Axis-1 hstack()
import numpy as np import numpy as np
ls1=[1,2,3] ls1=[1,2,3]
ls2=[4,5,6] ls2=[4,5,6]
ls3=[7,8,9] ls3=[7,8,9]
ls4=[10,11,12] ls4=[10,11,12]
x=np.array([ls1,ls2]) x=np.array([ls1,ls2])
y=np.array([ls3,ls4]) y=np.array([ls3,ls4])
a=np.concatenate((x,y),axis=0) a=np.concatenate((x,y),axis=1)
[[ 1 2 3] [[ 1 2 3 7 8 9]
[ 4 5 6] [ 4 5 6 10 11 12]]
[ 7 8 9]
[10 11 12]]
Axis=None
import numpy as np
ls1=[1,2,3]
ls2=[4,5,6]
ls3=[7,8,9]
ls4=[10,11,12]
x=np.array([ls1,ls2])
y=np.array([ls3,ls4])
a=np.concatenate((x,y),axis=None)
[ 1 2 3 4 4 5 6 4 7 8 9 10 11 12] outpur
Subset : part of array
Contiguous subset :- divide array without any condition
1. hsplit() : divide an array in equal parts horizontally(cols)
import numpy as np [array([[1, 2],
ls1=[1,2,3,4] [4, 5]]), array([[3, 4],
ls2=[4,5,6,4] [6, 4]])]
x=np.array([ls1,ls2])
y=np.hsplit(x,2)
2. vsplit():divide an array in equal parts horizontally(cols)
import numpy as np
ls1=[1,2,3,4]
[array([[1, 2, 3, 4]]),
ls2=[4,5,6,4] array([[4, 5, 6, 4]])]
x=np.array([ls1,ls2])
y=np.vsplit(x,2)
3. split():divide an array in equal parts horizontally or vertically(
import numpy as np [array([1, 2]), array([3, 4]), array([5, 6]),
ls1=[1,2,3,4,5,6,7,8] array([7, 8])]
x=np.array([ls1])
y=np.split(x,4)
import numpy as np [array([1, 2]), array([3, 4, 5]), array([6, 7,
ls1=[1,2,3,4,5,6,7,8] 8])]
x=np.array([ls1])
y=np.split(x,[2,5])
# 0:2 2:5 5:
import numpy as np [array([[1, 2, 3, 4, 5],
ls1=[1,2,3,4] [4, 5, 6, 4, 6]]), array([[2, 3, 6, 7, 8]]),
ls2=[4,5,6,4] array([], shape=(0, 5), dtype=int32)]
ls3=[2,3,6,7]
x=np.array([ls1,ls2])
y=np.split(x,[2,5],axis=0)
import numpy as np [array([[1, 2],
ls1=[1,2,3,4,5] [4, 5],
ls2=[4,5,6,4,6] [2, 3]]), array([[3, 4, 5],
ls3=[2,3,6,7,8] [6, 4, 6],
x=np.array([ls1,ls2,ls3]) [6, 7, 8]]), array([], shape=(3, 0),
y=np.split(x,[2,5],axis=1) dtype=int32)]
print(y)
Contiguous subset :- divide array with condition
import numpy as np
ls1=[1,2,3,4]
[2 4 4 6 4]
ls2=[4,5,6,4]
x=np.array([ls1,ls2])
c=np.mod(x,2)==0
y=np.extract(c,x)
print(y)
Operations on array
1. Arithmetic operation
1) Addition +
2) Multiplication *
3) Subtraction –
4) Exponent **
5) Matrix multiplication @
6) Division /
7) Remainder %
import numpy as np [ 6 8 10 12]
x=np.array([1,2,3,4]) [-4 -4 -4 -4]
y=np.array([5,6,7,8]) [ 5 12 21 32]
print(x+y) [ 1 8 27 64]
print(x-y) [0.2 0.33333333 0.42857143 0.5 ]
print(x*y) [1 2 3 4]
print(x**3)
print(x/y)
print(x%y)
import numpy as np [[6 8]
x=np.array([[1,2],[4,5]]) [6 7]]
y=np.array([[5,6],[2,2]]) [[-4 -4]
print(x+y) [ 2 3]]
print(x-y) [[ 5 12]
print(x*y) [ 8 10]]
print(x@y) [[ 9 10]
print(x**3) [30 34]]
print(x/y) [[ 1 8]
print(x%y) [ 64 125]]
[[0.2 0.33333333]
[2. 2.5 ]]
[[1 2]
[0 1]]
2. Transpose :- convert rows into cols and cols into rows
import numpy as np [[1 4]
x=np.array([[1,2,3],[4,5,6]]) [2 5]
y=np.transpose(x) [3 6]]
print(y)
3. Sorting :- Arrange in ascending order
import numpy as np [-3 0 1 2 4 6 7 8]
a = np.array([1,0,2,-3,6,8,4,7])
a.sort()
print(a)
import numpy as np [[4 1 1 2]
a = np.array([[4,3,1,2],[5,1,2,3]]) [5 3 2 3]]
a.sort(axis=0) #cols
print(a)
import numpy as np [[1 2 3 4]
a = np.array([[4,3,1,2],[5,1,2,3]]) [1 2 3 5]]
a.sort(axis=1) # rows by default
print(a)
Load data in numpy array from external file
We can import data from csv or text file in a numpy array using loadtext() function
import numpy as np
studentdata = np.loadtxt('D:/NCERT/student.csv', skiprows=1, delimiter=',')
print(studentdata)
Output
[[ 1. 34. 44. 54.]
[ 2. 35. 45. 55.]
[ 3. 36. 46. 56.]
[ 4. 37. 47. 57.]
[ 5. 38. 48. 58.]]
import numpy as np
stud1, stud2, stud3, stud4,stud5 = np.loadtxt('D:/NCERT/student.csv', skiprows=1, delimiter=',')
print(stud1)
print(stud2)
print(stud3)
print(stud4)
print(stud5)
[ 1. 34. 44. 54.]
[ 2. 35. 45. 55.]
[ 3. 36. 46. 56.]
[ 4. 37. 47. 57.]
[ 5. 38. 48. 58.]
import numpy as np
stud1, stud2, stud3, stud4 = np.loadtxt('D:/NCERT/student.csv', skiprows=1,
delimiter=',',unpack=True)
print(stud1)
print(stud2)
print(stud3)
print(stud4)
[1. 2. 3. 4. 5.]
[34. 35. 36. 37. 38.]
[44. 45. 46. 47. 48.]
[54. 55. 56. 57. 58.]
Using NumPy.genfromtxt()
From this function if any blank value it is replaced by nan value
import numpy as np
studentdata = np.genfromtxt('D:/NCERT/student.csv', skip_header=1, delimiter=',')
print(studentdata)
[[ 1. 34. 44. 54.]
[ 2. 35. 45. nan]
[ 3. 36. 46. 56.]
[ 4. 37. 47. 57.]
[ 5. 38. 48. 58.]]
import numpy as np
studentdata = np.genfromtxt('D:/NCERT/student.csv', skip_header=1,filling_values=-999,
delimiter=',')
print(studentdata)
[[ 1. 34. 44. 54.]
[ 2. 35. 45. -999.]
[ 3. 36. 46. 56.]
[ 4. 37. 47. 57.]
[ 5. 38. 48. 58.]]
sAvIng numPy ArrAys In fIles on dIsk
import numpy as np
studentdata = np.genfromtxt('D:/NCERT/student.csv', skip_header=1,filling_values=-999,
delimiter=',')
np.savetxt('D:/NCERT/testout.txt',
studentdata, delimiter=',', fmt='%i')
print(studentdata)