numpy C2
numpy C2
ASST. PROFESSOR
CEA DEPT.
GLA UNIVERSITY,
MATHURA
numpy
(numerical python)
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
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. ]
a.copy() and a.view()
a.copy() will create a new copy while a.view() just
creates a new reference to the existing object.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = a.copy()
a[0] = 42
print(a) #[42 2 3 4 5]
print(b) #[1 2 3 4 5]
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = a.view()
a[0] = 42
print(a) #[42 2 3 4 5]
print(b) #[42 2 3 4 5]
Shape of an Array
a.shape
import numpy as np
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a.shape) #(2,4)
Reshaping arrays
a.reshape()
import numpy as np
a=
np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12])
b = a.reshape(4, 3) #OR np.reshape(a,
(4,3))
print(b)
Can we Reshape Into any Shape?
Yes, as long as the elements required for
reshaping are equal in both shapes.
Unknown Dimension