numpy Part-1
numpy Part-1
ASST. PROFESSOR
CEA DEPT.
GLA UNIVERSITY,
MATHURA
numpy
(numerical python)
Python
C
C++
Command to install numpy
pip install numpy
numpy.array(list or tuple)
import numpy as np
k=np.array(38)
print(k)
2D array or Matrix is also called 2nd order
Tensors.
3D array is also called 3rd order Tensors.
ndim Attribute
It is used to check the dimension of the array.
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim) 0
print(b.ndim) 1
print(c.ndim) 2
print(d.ndim) 3
An array can have any number of dimensions. When
the array is created, you can define the number of
dimensions by using the ndmin argument
import numpy as np
a = np.array([1, 2, 3, 4], ndmin=5)
print(a)
print(‘Number of dimensions :', a.ndim)
Output:
[[[[[1 2 3 4]]]]]
Number of dimensions : 5
Accessing element
To access elements from 2-D arrays we
can use comma separated integers
representing the dimension and the
index of the element.
import numpy as np
a = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print(a[0, 1]) # instead of
a[0][1]
import numpy as np
a = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
print(a[0:2, 1:4])
Datatype of Array and Datatype of
elements
import numpy as np
a=np.array([1,2,3,4])
print(type(a)) # <class
'numpy.ndarray'>
Output:-
[1. 2. 3. 4. ]
Converting Data Type on Existing
Arrays
astype()
import numpy as np
import numpy as np
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a.shape) #(2,4)
import numpy as np
a = np.array([1, 2, 3, 4], ndmin=5)
print(a)
print(a.shape) #(1,1,1,1,4)
Reshaping arrays
a.reshape()
import numpy as np
arr =
np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12])
newarr = arr.reshape(4, 3)
print(newarr)
Can we Reshape Into any Shape?
Yes, as long as the elements required for
reshaping are equal in both shapes.
Returns Copy or View?
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8])
b=a.reshape(2,4)
print(b.base)