VINAY AGRAWAL
ASST. PROFESSOR
CEA DEPT.
GLA UNIVERSITY,
MATHURA
numpy
(numerical python)
1. It is a module used for working with arrays.
2. It was created by Travis Oliphant in 2005.
3. In Python, we have lists that serve the purpose
of arrays, but they are slow to process.
4. numpy aims to provide an array object that is
up to 50x faster than traditional Python
lists.
5. The array object in numpy is called ndarray.
Why is numpy Faster Than Lists?
numpy arrays are stored at one
continuous place in memory unlike
lists, so processes can access and
manipulate them very efficiently. This
behavior is called locality of reference
in computer science.
Also it is optimized to work with latest
CPU architectures.
In which language numpy is written?
Python
C
C++
Command to install numpy
pip install numpy
numpy.array(list or tuple)
1. Convert List into Array
import numpy
L=[1,2,10,20] # or tuple
a=numpy.array(L)
print(a)
Output:[1 2 10 20]
2. Check the version of installed numpy
print(numpy.__version__)
0-D Arrays
0-D arrays, or Scalars, are the elements in an
array. Each value in an array is a 0-D array.
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]
We can also use Negative indexes
Accessing elements by Slicing
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'>
print(a.dtype) # int32 Datatype
of element
Creating Arrays With a Defined Data
Type
arr = np.array([1, 2, 3, 4], dtype=float)
Output:-
[1. 2. 3. 4. ]
Converting Data Type on Existing
Arrays
astype()
import numpy as np
a = np.array([1.1, 2.1, 3.1])
b= a.astype(int) # or a.astype(‘i’)
print(b) #[1 2 3]
print(b.dtype)
import numpy as np
a = np.array([1, 0, 3])
b = a.astype(bool)
print(b) #[True False True]
print(b.dtype)
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]
b.base
b.base will return None if it creates a
new copy.
Shape of an Array
a.shape
a.shape that returns a tuple
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)
If it is None, it means it is a copy else it
is View
It is view because it doesn’t return None.
Unknown Dimension
You are allowed to have one "unknown"
dimension.
Meaning that you do not have to specify an exact
number for one of the dimensions in the reshape
method. Pass -1 as the value, and NumPy will
calculate this number for you.
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8])
b = a.reshape(2, 2, -1)
print(b)
Note: We can not pass -1 to more than one
dimension.
Flattening the arrays
Flattening array means converting a multidimensional
array into a 1D array.
import numpy as np
a= np.array([[1, 2, 3], [4, 5, 6]])
b = a.reshape(-1)
print(b)
Note: There are a lot of functions for changing the
shapes of arrays in numpy flatten, ravel and also for
rearranging the elements rot90, flip, fliplr, flipud etc.
These fall under Intermediate to Advanced section of
numpy.