Numpy @CodeProgrammer
Numpy @CodeProgrammer
Data analysisi involves a broad set of activites to clean, process and transform a data collection
to procure meaningful insights from it.
NumPy arrays use less memory than Python lists and allow you to specify data types,
helping your code run even more efficiently.
What is an Array?
You can access elements in an array using various methods, like indexing with
numbers, booleans, or even other arrays. Arrays can have multiple dimensions,
which is called the rank (like rows and columns in a table), and the shape
describes the size along each dimension.
To create a NumPy array, you can start with a Python list, using nested lists for
data with multiple dimensions, such as a 2D or 3D array.
We often shorten numpy to np when importing it, like this: import numpy as np .
This convention is widely used and makes code easier to read and understand.
It’s recommended to always use np for consistency, so others working with your code can
easily follow along.
[1, 2, 3, 4]
Out[2]:
array([1, 2, 3, 4])
Out[3]:
[1 2 3 4]
In [5]: np.array([])
array([], dtype=float64)
Out[5]:
dtype
The desired data-type for the array. If not given, then the type willbe determined as the
minimum type required to hold the objects in thesequence.
type: This is a general Python function that gives you the type of any object, like whether
something is a list, integer, float, or in this case, a NumPy array. For example, calling type(arr) on
a NumPy array arr would return <class 'numpy.ndarray'>.
dtype: This is specific to NumPy and stands for data type. It tells you the type of data stored in
the array, such as integers, floats, or strings. For example, arr.dtype might return int32 if arr is
storing 32-bit integers.
dtype tells you what kind of elements are inside the array (like int32 or float64).
4
Out[6]:
(4,)
Out[7]:
1
Out[8]:
NumPy Arrays: Use less memory because they store items in one block. This
makes them faster to work with, especially with large data. ?Python Lists: Store
items separately, which takes more memory and can be slower for big datasets.
Speed:
Array: Much faster for math operations (like adding or multiplying numbers)
because NumPy is written in a fast programming language (C).
List: Slower for math operations, as Python lists aren’t designed with speed in
mind for big calculations.
Data type:
Array:All items have to be the same type (like all numbers or all strings). This
makes NumPy faster and more predictable.
List:Items can be different types (like mixing numbers and words in one list),
which makes them flexible but slower.
Mathematical operations:
Array: You can do math on the whole array at once (like multiplying every item by
2). This is called “element-wise” operations, and it’s much quicker and easier than
doing each item one by one.
List:You need a loop or list comprehension to perform math on each item, which
takes more code and is slower.
Multi- di data:
Array:Easily handle 2D, 3D, and higher-dimensional data (like tables or grids),
which is useful in data science and machine learning.
List: Can handle multi-dimensional data, but it gets tricky and isn’t as smooth as
NumPy for things like tables or matrices.
array([1, 2, 3, 4])
Out[9]:
In [11]: ar = np.array([[45,34,12,2],[24,55,3,22]])
ar
# 2D array is an metrix
In [15]: b = np.array(l2)
b
array([[1, 2, 3, 4],
Out[15]:
[5, 6, 7, 8]])
2
Out[17]:
8
Out[18]:
(2, 4)
Out[19]:
In [20]: type(l)
list
Out[20]:
numpy.ndarray
Out[21]:
dtype('int32')
Out[22]:
In [13]: # 3D ---- Tensor
np.array ( [[2,3,33,4,45],[23,45,56,66,2],[357,523,32,24,2],[32,32,44,33,234]])
[3.2, 2.3, 4]
Out[24]:
In [26]: r1 = np.array(r)
r1
# it is creating the 4 into float format i.e 4,0 because othe integers aare in float f
array([3.2, 2.3, 4. ])
Out[26]:
In [27]: type(r1)
numpy.ndarray
Out[27]:
In [29]: r1.dtype # it is showing deta type of all the elements present in the array i.e that 6
dtype('float64')
Out[29]:
In [32]: lx = np.array([[[1,2,3,4],
[5,6,7,8]],
[[1,3,5,7],
[2,4,6,8]]])
lx
array([[[1, 2, 3, 4],
Out[32]:
[5, 6, 7, 8]],
[[1, 3, 5, 7],
[2, 4, 6, 8]]])
In [33]: lx.ndim # it is 3D
3
Out[33]:
In [35]: c = np.array([[1,2,3,4],
[2,3,4,5]])
c
array([[1, 2, 3, 4],
Out[35]:
[2, 3, 4, 5]])
array([[1, 2, 3, 4],
Out[36]:
[2, 3, 4, 5]])
array([[1, 2, 3, 4],
Out[38]:
[2, 3, 4, 5]])
Lets take any random list i.e l = [4, 3, 'hi'] in this list acoording to storage element 4 can be
stroe in 1 bit data element 3 can store 2 bit data and 'hi' is storing lets say 3 bit data here
but in case of array ; every element into the list array stores equal storage i.e from l list
every element stores equal lets say 3 3 3 bit of storage each
numpy shows the string data in unicode formate
In [19]: np.array([[1,2,'hi'],[3,4,5],['me',3,1]])
Zeros
np.zeros(shape, dtype) is used to create an array that is filled entirely with zeros.
By default, the data type (dtype) of the elements is float64, but you can specify a different
type if needed, such as int.
array([0., 0.])
Out[22]:
Ones
np.ones(shape, dtype) is used to create an array where every element is set to 1.
The default data type is also float64, but it can be changed to other types such as int or
bool if needed.
In [ ]:
In [ ]:
In [25]: a = np.full((4,3),8)
a
array([[8, 8, 8],
Out[25]:
[8, 8, 8],
[8, 8, 8],
[8, 8, 8]])
Random Matrix
Random function
it will give matrix of random values
it will be always between 0 to 1 only
each time when you runs the cell again , it will give diff values everytime
1D random array
In [112… np.random.random(4)
# random array with 4 element
2D random array
In [113… np.random.random((2,3))
#random array of 2 rows and 3 columns
3D random array
In [114… np.random.random((2,3,5))
Randint
it will generate random integer no between the given range
by default n starts from 0
num can be repeated
gives random numbers between given range
In [115… np.random.randint(2,13)
# it will give any random no between 2 and 13
2
Out[115]:
array([5, 5, 2, 3, 7])
Out[116]:
In [118… np.random.randint(5) #-------> by default range will start from 0 till given no i.e
1
Out[118]:
Rand
it will give float value between 0 to 1
0.772604817610183
Out[120]:
In [122… np.random.rand(2,3) # 2D
In [123… np.random.rand(3,3,2)
# 3 matix, 3 rows 2 column
array([[[0.03749444, 0.69994934],
Out[123]:
[0.91090628, 0.10770802],
[0.74155137, 0.59147709]],
[[0.11597925, 0.67741489],
[0.06385999, 0.88252133],
[0.87412051, 0.35581526]],
[[0.95294118, 0.90267936],
[0.78386692, 0.18538943],
[0.96224071, 0.94047315]]])
Randn
it gives any random no ,positive or negative also
In [125… np.random.randn() ## whenever you run this , it will give differnt differnt positive
0.9266949987087295
Out[125]:
In [126… np.random.randn(4)
In [127… np.random.randn(2,3)
In [128… np.random.randn(3,2,2)
[[-0.53918607, -0.83429102],
[ 2.21677243, -0.16611044]],
[[ 0.09675731, 1.60249978],
[ 1.00712861, 1.11904854]]])
Uniform
it returns random float no between given range
the numbers cant be repeted here
if range is not given and only one value is given , it wil take by default from 0 to that numer
as a range
if nothing given in the (), it will generat any random float value between 0 to 1
In [129… np.random.uniform(2,3)
2.5812577858766685
Out[129]:
In [130… np.random.uniform(2,5,10)
In [131… np.random.uniform(2)
1.2549953472864535
Out[131]:
In [132… np.random.uniform()
0.49983041570496933
Out[132]:
Choice
here we have to give sequence
this funciton will give any random value from the given sequence
if not range given , only 1 value given then it will take range from 0 to that number by
default abd generate random number
elements can be repeted here
if you dont want rpeting element (replace = False)
In [133… np.random.choice([1,3,4,5,6,9,7])
7
Out[133]:
In [134… np.random.choice([1,3,4,5,6,9,7], 3)
# (sequence, no of element you want)
array([5, 4, 6])
Out[134]:
array([5, 2, 5, 7, 8, 5, 4, 5, 2, 6, 1, 6, 9, 0, 7, 1, 1, 6, 4, 0, 1, 3,
Out[138]:
5, 5, 7, 7, 2, 3, 3, 1])
7
Out[139]:
array([6, 7, 9, 5])
Out[142]:
# it will throw error because , we told python not to repet the vslue and give 10 elem
# than the demanded number , it will thow error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[144], line 1
----> 1 np.random.choice([1,3,4,5,6,9,7], 10, replace = False)
array([7, 9, 1, 7, 1, 3, 4, 3, 9, 9])
Out[145]:
In [ ]:
In [ ]:
arange
arange can be called with a varying number of positional arguments
designed to generate the sequence of numerical values like int or float
ex :
2] np.arange(1,10,2) #(start,stop,step)
Note: arange function is specificaly designed for only numerical values , it wont work with non
numeric types like stirng or objects
[2, 4, 6, 8]
Out[50]:
array([2, 4, 6, 8])
Out[54]:
array([2, 4, 6, 8])
Out[56]:
Linespace
Linear space
Linearly Seperable in given range at equal distace it creates points
by default it will give float value
array([ 1., 12., 23., 34., 45., 56., 67., 78., 89., 100.])
Out[32]:
In [33]: np.linspace(1,100,10, dtype = int) # divide , and give integer data type
array([ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100])
Out[33]:
In [34]: np.linspace(1,20,2,dtype='str')
np.linspace(1,10,3,endpoint = False)
Identity Matrix
indentity matrix is that diagonal items will be ones and evrything will be zeros
In [36]: np.identity(4)
In [37]: np.identity(5)
In [38]: np.identity(3)
In [39]: np.identity(7)
In [ ]:
In [ ]:
In [ ]: # ML
- supervised learnng # lable
- unsupervised learning
- semi-supervised learning
- reinforcement learning
In [71]: h = [[[1,2,3,4],[2,3,4,5],
[3,4,5,6],[4,5,6,7]],
[[1,2,3,4],[2,3,4,5],
[3,4,5,6],[4,5,6,7]],
[[1,2,3,4],[2,3,4,5],
[3,4,5,6],[4,5,6,7]]]
ha= np.array(h)
ha
array([[[1, 2, 3, 4],
Out[71]:
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]],
[[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]],
[[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]]])
In [72]: ha.shape
(3, 4, 4)
Out[72]:
reahape
changing/ modifying the shape
the product of arguments we are passing in reshape , should be equal to the no of items
preset inside the array
In [3]: np.arange(1,10).reshape(3,3)
# range = 1 to 9
# shape we want = 3 ,3 (3*3 = 9)
#- as we provide range till 9 , it will only work with the above shapes given
#- it wont work other than these
array([[1, 2, 3],
Out[3]:
[4, 5, 6],
[7, 8, 9]])
In [4]: np.arange(1,10).reshape(9,1)
array([[1],
Out[4]:
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
In [5]: np.arange(1,10).reshape(1,9)
array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
Out[5]:
In [7]: np.arange(1,10).reshape(2,3)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[7], line 1
----> 1 np.arange(1,10).reshape(2,3)
In [9]: np.arange(1,13).reshape(2,6)
array([[ 1, 2, 3, 4, 5, 6],
Out[9]:
[ 7, 8, 9, 10, 11, 12]])
In [10]: np.arange(1,13).reshape(3,4)
array([[ 1, 2, 3, 4],
Out[10]:
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
In [11]: np.arange(1,13).reshape(4,3)
array([[ 1, 2, 3],
Out[11]:
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
In [12]: np.arange(1,13).reshape(6,2)
array([[ 1, 2],
Out[12]:
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12]])
In [13]: np.arange(1,13).reshape(12,1)
array([[ 1],
Out[13]:
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12]])
In [14]: np.arange(1,13).reshape(1,12)
In above reshape exapmples we created arrays directy by giving range and shape
values
In [15]: h = [[[1,2,3,4],[2,3,4,5],
[3,4,5,6],[4,5,6,7]],
[[1,2,3,4],[2,3,4,5],
[3,4,5,6],[4,5,6,7]],
[[1,2,3,4],[2,3,4,5],
[3,4,5,6],[4,5,6,7]]]
ha= np.array(h)
ha
array([[[1, 2, 3, 4],
Out[15]:
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]],
[[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]],
[[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]]])
In [16]: ha.reshape((4,3,4))
array([[[1, 2, 3, 4],
Out[16]:
[2, 3, 4, 5],
[3, 4, 5, 6]],
[[4, 5, 6, 7],
[1, 2, 3, 4],
[2, 3, 4, 5]],
[[3, 4, 5, 6],
[4, 5, 6, 7],
[1, 2, 3, 4]],
[[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]]])
In [77]: ha.reshape((2,2,3,4))
array([[[[1, 2, 3, 4],
Out[77]:
[2, 3, 4, 5],
[3, 4, 5, 6]],
[[4, 5, 6, 7],
[1, 2, 3, 4],
[2, 3, 4, 5]]],
[[[3, 4, 5, 6],
[4, 5, 6, 7],
[1, 2, 3, 4]],
[[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]]]])
In [81]: ha.reshape((3,2,4,2))
array([[[[1, 2],
Out[81]:
[3, 4],
[2, 3],
[4, 5]],
[[3, 4],
[5, 6],
[4, 5],
[6, 7]]],
[[[1, 2],
[3, 4],
[2, 3],
[4, 5]],
[[3, 4],
[5, 6],
[4, 5],
[6, 7]]],
[[[1, 2],
[3, 4],
[2, 3],
[4, 5]],
[[3, 4],
[5, 6],
[4, 5],
[6, 7]]]])
In [18]: ha.reshape((2,6))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[18], line 1
----> 1 ha.reshape((2,6,3))
In [90]: ha.reshape((8,4))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[90], line 1
----> 1 ha.reshape((8,4))
In [91]: ha.reshape((20))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[91], line 1
----> 1 ha.reshape((20))
array([[[1, 2, 3, 4],
Out[92]:
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]],
[[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]],
[[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]]])
array([1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 1, 2, 3, 4, 2, 3,
Out[93]:
4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6,
4, 5, 6, 7])
In [94]: b
array([[1, 2, 3, 4],
Out[94]:
[5, 6, 7, 8]])
array([[1, 5],
Out[96]:
[2, 6],
[3, 7],
[4, 8]])
Identity matrix
only digonal items will be 1 and other remaining all will be zero
In [19]: np.identity(3)
In [20]: np.identity(6)
In [21]: np.identity(5)
array([[1., 0., 0., 0., 0.],
Out[21]:
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
In [40]: a = np.array([32,33,12])
a
In [42]: type(a)
numpy.ndarray
Out[42]:
In [43]: a.dtype
dtype('int32')
Out[43]:
a.astype('str')
In [45]: a.astype('bool')
In [46]: a.astype(float)
In [48]: z1 = np.array(range(1,10))
z1
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Out[48]:
In [56]: z1 = np.arange(12).reshape(4,3)
z1
array([[ 0, 1, 2],
Out[56]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [63]: # addition
z1 + 34 # adding 34 in each element
In [62]:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[62], line 1
----> 1 z3 = np.random.random().reshape(3,4)
In [65]: # substraction
z1 - 20
In [66]: # multiplication
z1 *2
array([[ 0, 2, 4],
Out[66]:
[ 6, 8, 10],
[12, 14, 16],
[18, 20, 22]])
In [68]: # division
z1 / 2
array([[0. , 0.5, 1. ],
Out[68]:
[1.5, 2. , 2.5],
[3. , 3.5, 4. ],
[4.5, 5. , 5.5]])
In [74]: # modulo
z1 % 2
array([[0, 1, 0],
Out[74]:
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]], dtype=int32)
array([[0, 0, 1],
Out[75]:
[1, 2, 2],
[3, 3, 4],
[4, 5, 5]], dtype=int32)
Relational operation
The relational operators are also known as comparison operators
their main function is to return either a true or false based on the value of operands.
In [76]: z1
array([[ 0, 1, 2],
Out[76]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [77]: z1 > 30
In [78]: z1 < 20
In [79]: z1 == 30
Vector Operation
applied on both numpy array
In [80]: z1
array([[ 0, 1, 2],
Out[80]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [81]: z2
ValueError: operands could not be broadcast together with shapes (4,3) (3,4)
In [89]: z3 = np.arange(12,24).reshape(4,3)
z3
In [90]: z1
array([[ 0, 1, 2],
Out[90]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [91]: z3
In [95]: z1*z3
In [96]: z1 / z3
In [97]: z1 - z3
z1 == z3
In [100… z1 > z3
In [101… z1< z3
Indexing in array
Normal way
integer array indexing
boolean array indexing
In [103… q = [[1,2,3,4],[4,5,6,7],[6,7,8,9]]
qa = np.array(q)
qa
# 2D data
array([[1, 2, 3, 4],
Out[103]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
array([1, 2, 3, 4])
Out[104]:
3
Out[105]:
4
Out[106]:
array([5, 9])
Out[108]:
In [109… qa[[2,0],[1,0]]
array([7, 1])
Out[109]:
In [110… qa[[0,0],[1,2]]
array([2, 3])
Out[110]:
In [117… qa
array([[1, 2, 3, 4],
Out[117]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
In [120… p3 = np.arange(8).reshape(2,2,2)
p3
# 3d consist of 2 2D array
# array 1 = 0th
# row 1 = 0th
# row 2 = 1st
# array 2 = 1st
# row 1 = 0th
# row 2 = 1st
array([[[0, 1],
Out[120]:
[2, 3]],
[[4, 5],
[6, 7]]])
7
Out[123]:
In [125… p3[0,1,1]
3
Out[125]:
In [127… p3[1,1,0]
6
Out[127]:
In [ ]:
In [112… qa
array([[1, 2, 3, 4],
Out[112]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
In [113… qa[qa % 2 == 0]
# here it will give all the coordinaates form the array which are ultiple of 2 i.e it
array([2, 4, 4, 6, 6, 8])
Out[113]:
In [114… qa[(qa % 2 == 0) & (qa % 3 ==0)] # we cannto use and here , we have to use bitwise &
array([6, 6])
Out[114]:
array([2, 3, 4, 4, 6, 6, 8, 9])
Out[115]:
array([1, 3, 5, 7, 7, 9])
Out[116]:
slicing
1 D slicing
In [136… a = np.arange(1,10)
a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Out[136]:
In [137… a[2:5]
array([3, 4, 5])
Out[137]:
In [138… a[3:5]
array([4, 5])
Out[138]:
array([1, 3])
Out[139]:
2 D Slicing
In [4]: pp = np.arange(12).reshape(3,4)
pp
array([[ 0, 1, 2, 3],
Out[4]:
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [6]: pp[0,:]
#Here 0 represents first row and (:) represnts Total column
array([0, 1, 2, 3])
Out[6]:
In [7]: pp[:,2]
array([ 2, 6, 10])
Out[7]:
In [13]: pp[1:2,1:3]
array([[5, 6]])
Out[13]:
In [14]: pp[0:2,1:2]
array([[1],
Out[14]:
[5]])
In [15]: pp[1:2,0:3]
array([[4, 5, 6]])
Out[15]:
In [16]: pp[0:2,0:2]
array([[0, 1],
Out[16]:
[4, 5]])
In [17]: pp[0:2,1:3]
array([[1, 2],
Out[17]:
[5, 6]])
In [18]: pp[1:3,0:1]
array([[4],
Out[18]:
[8]])
In [19]: pp[::2,::3]
array([[ 0, 3],
Out[19]:
[ 8, 11]])
In [20]: pp[::2,::2]
array([[ 0, 2],
Out[20]:
[ 8, 10]])
In [21]: pp[1::2,0::3]
array([[4, 7]])
Out[21]:
In [22]: pp[0::2,1::2]
# only those elements are taken which are found to be common in this
array([[ 1, 3],
Out[22]:
[ 9, 11]])
In [23]: pp[::2]
array([[ 0, 1, 2, 3],
Out[23]:
[ 8, 9, 10, 11]])
In [25]: pp[0,::2]
array([0, 2])
Out[25]:
In [26]: pp[::,3]
array([ 3, 7, 11])
Out[26]:
In [27]: pp[0:2,1:]
array([[1, 2, 3],
Out[27]:
[5, 6, 7]])
In [28]: pp[0:2,0::3]
array([[0, 3],
Out[28]:
[4, 7]])
In [29]: pp[1::2,1:3]
array([[5, 6]])
Out[29]:
In [30]: pp[1:3,0::2]
array([[ 4, 6],
Out[30]:
[ 8, 10]])
In [31]: pp[0:2,1::2]
array([[1, 3],
Out[31]:
[5, 7]])
In [119… qa
array([[1, 2, 3, 4],
Out[119]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
array([[2, 3],
Out[121]:
[5, 6]])
In [130… qa[1:,1::2]
# row wise = from 1 to last
# col wise = from 1 to last with step of 2
array([[5, 7],
Out[130]:
[7, 9]])
In [131… qa[::2,1::2]
array([[2, 4],
Out[131]:
[7, 9]])
In [132… qa
array([[1, 2, 3, 4],
Out[132]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
In [134… qa[0:2,1::2]
array([[2, 4],
Out[134]:
[5, 7]])
Slicing 3D
In [33]: d3 = np.arange(36).reshape(3,4,3)
d3
array([[[ 0, 1, 2],
Out[33]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
In [39]: d3[0]
array([[ 0, 1, 2],
Out[39]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [34]: d3[1]
In [36]: d3[2]
In [41]: d3[0,1]
array([3, 4, 5])
Out[41]:
In [42]: d3[0,0]
array([0, 1, 2])
Out[42]:
In [43]: d3[0,2]
array([6, 7, 8])
Out[43]:
In [44]: d3[0,3]
In [45]: d3[1,0]
In [46]: d3[2,0]
In [47]: d3[1,1]
In [48]: d3[1,2]
In [50]: d3[1,3]
In [52]: d3[2,1]
array([27, 28, 29])
Out[52]:
In [53]: d3[2,2]
In [54]: d3[2,3]
In [55]: d3[2::]
In [56]: d3[::2]
array([[[ 0, 1, 2],
Out[56]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
In [58]: d3
array([[[ 0, 1, 2],
Out[58]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
OPration on Array
In [126… qa
array([[1, 2, 3, 4],
Out[126]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
In [128… qa1 = qa + 1
qa1
# concatinate by adding 1
array([[ 2, 3, 4, 5],
Out[128]:
[ 5, 6, 7, 8],
[ 7, 8, 9, 10]])
In [131… qa ** 2 # power
array([[ 1, 4, 9, 16],
Out[131]:
[16, 25, 36, 49],
[36, 49, 64, 81]])
In [133… qa
array([[1, 2, 3, 4],
Out[133]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
In [136… qa = qa + 1
qa
# also written as qa +=1
array([[ 4, 5, 6, 7],
Out[136]:
[ 7, 8, 9, 10],
[ 9, 10, 11, 12]])
In [140… l2 = np.array(l)
l2
array([[1, 2, 3, 4],
Out[140]:
[2, 3, 4, 5]])
array([[3, 6, 9, 2],
Out[60]:
[1, 8, 3, 6]])
In [145… l23 = l2 + l3
l23
In [146… l3 % l2
array([[0, 0, 0, 2],
Out[146]:
[1, 2, 3, 1]])
In [147… qa
array([[ 4, 5, 6, 7],
Out[147]:
[ 7, 8, 9, 10],
[ 9, 10, 11, 12]])
In [148… l2
array([[1, 2, 3, 4],
Out[148]:
[2, 3, 4, 5]])
In [149… l2 + qa # bwcause qa is 1D
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[149], line 1
----> 1 l2 + qa
ValueError: operands could not be broadcast together with shapes (2,4) (3,4)
In [152… l2[0]
array([1, 2, 3, 4])
Out[152]:
array([[ 5, 7, 9, 11],
Out[151]:
[ 8, 10, 12, 14],
[10, 12, 14, 16]])
In [153… l2 * l3 # element wise multiplication
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Transpose
Converts rows in to clumns ad columns into rows
array([[ 0, 1, 2, 3],
Out[59]:
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [63]: # method 1
array([[ 0, 4, 8],
Out[63]:
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
In [65]: #method 2
pp.T
array([[ 0, 4, 8],
Out[65]:
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
In [66]: d3
array([[[ 0, 1, 2],
Out[66]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
In [67]: d3.T
[[ 1, 13, 25],
[ 4, 16, 28],
[ 7, 19, 31],
[10, 22, 34]],
[[ 2, 14, 26],
[ 5, 17, 29],
[ 8, 20, 32],
[11, 23, 35]]])
Ravel
Concerts any dimentionala array 1D array
In [68]: pp
array([[ 0, 1, 2, 3],
Out[68]:
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [70]: pp.ravel()
In [71]: d3
array([[[ 0, 1, 2],
Out[71]:
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
In [72]: d3.ravel()
Stacking
Stacking is the concept of joining arrays in NumPy.
In [77]: a = np.arange(8).reshape(2,4)
a2 = np.arange(8,16).reshape(2,4)
print(a)
print(a2)
[[0 1 2 3]
[4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]
In [81]: np.hstack((a,a2))
In [89]: np.vstack((a,a2))
array([[ 0, 1, 2, 3],
Out[89]:
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Splitting
opposite of stacking
it seperates the array as per given
In [84]: a
array([[0, 1, 2, 3],
Out[84]:
[4, 5, 6, 7]])
In [85]: a2
In [91]: np.hsplit(a,2)
[array([[0, 1],
Out[91]:
[4, 5]]),
array([[2, 3],
[6, 7]])]
In [94]: pp
array([[ 0, 1, 2, 3],
Out[94]:
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [96]: np.hsplit(pp,2)
[array([[0, 1],
Out[96]:
[4, 5],
[8, 9]]),
array([[ 2, 3],
[ 6, 7],
[10, 11]])]
In [101… np.vsplit(pp,3)
In [ ]:
Dot
In [154… l_mult = l2.dot(l3)
l_mult
# dot function will give result like matrix multiplication (1st row multiply by 1st co
# but for matrix multiplication , no of rows should be equal to no of columns
# here is 2 row and 4 column
# hence it will throw error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[154], line 1
----> 1 l_mult = l2.dot(l3)
2 l_mult
In [62]: l3
array([[3, 6, 9, 2],
Out[62]:
[1, 8, 3, 6]])
In [61]: l3.T
array([[3, 1],
Out[61]:
[6, 8],
[9, 3],
[2, 6]])
In [156… l2.dot(l3.T)
array([[50, 50],
Out[156]:
[70, 68]])
In [159… (l2.T).dot(l3)
In [160… l3.dot(l2.T)
array([[50, 70],
Out[160]:
[50, 68]])
In [5]: m = [[1,2,3,4],
[5,6,7,8],
[9,1,11,12]]
np.array(m)
array([[ 1, 2, 3, 4],
Out[5]:
[ 5, 6, 7, 8],
[ 9, 1, 11, 12]])
array to list
In [4]: import numpy as np
In [7]: p = mm.tolist()
p
# to make list of array
array([[3, 6, 9, 2],
Out[170]:
[1, 8, 3, 6]])
In [173… len(dir(np))
601
Out[173]:
In [174… pi
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[174], line 1
----> 1 pi
In [175… np.pi
3.141592653589793
Out[175]:
In [176… np.sin(np.pi)
1.2246467991473532e-16
Out[176]:
1.0
Out[177]:
In [178… np.sin(0)
0.0
Out[178]:
3.0
Out[179]:
In [180… np.exp
<ufunc 'exp'>
Out[180]:
7.38905609893065
Out[181]:
<ufunc 'log'>
Out[182]:
In [183… np.log(2)
0.6931471805599453
Out[183]:
In [184… np.log10(2)
0.3010299956639812
Out[184]:
In [186… m.log10(2)
0.3010299956639812
Out[186]:
In [188… a
array([1, 2, 3, 4])
Out[188]:
In [189… np.log(a)
In [190… np.log10(a)
In [197… np.array(q)
array([[1, 2, 3, 4],
Out[197]:
[4, 5, 6, 7],
[6, 7, 8, 9]])
In [ ]:
Sort
In [205… x = np.array([[11, 12, 33, 45],
[42, 53, 54, 71],
[61, 91, 82, 81]])
x
In [209… np.sort(e)
array([[1.5, 1.5, 1.5],
Out[209]:
[1.5, 1.5, 1.5]])
In [210… np.random.randn(4,4)
In [211… np.random.uniform(3,4)
3.941510537524191
Out[211]:
In [215… np.random.uniform(3,4, (2,3)) # it will give matrix of 2 by three in which all the no
append
The numpy.append() appends values along the mentioned axis at the end of the array
In [16]: a = np.random.randint(20,100,10)
a
array([92, 81, 43, 51, 91, 97, 96, 36, 66, 94])
Out[16]:
array([ 92, 81, 43, 51, 91, 97, 96, 36, 66, 94, 100])
Out[17]:
In [19]: b = np.random.randn(3,2)
b
In [20]: np.append(b,np.ones((b.shape[0],1)))
In [23]: np.append(b,np.ones((b.shape[0],1)),axis = 1)
Concatenate
numpy.concatenate() function concatenate a sequence of arrays along an existing axis.
Similar to stacking( hstack and vstack)
In [26]: a = np.arange(6,12).reshape(2,3)
b = np.arange(12,18).reshape(2,3)
In [27]: a
array([[ 6, 7, 8],
Out[27]:
[ 9, 10, 11]])
In [29]: b
array([[ 6, 7, 8],
Out[31]:
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]])
In [32]: np.concatenate((a,b),axis = 0)
array([[ 6, 7, 8],
Out[32]:
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]])
expand
With the help of Numpy.expand_dims() method, we can get the expanded dimensions of an
array
In [48]: v = np.random.randint(2,100,10)
v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[48]:
In [49]: v.shape
(10,)
Out[49]:
array([[56, 70, 63, 26, 65, 44, 19, 24, 86, 2]])
Out[50]:
array([[56],
Out[51]:
[70],
[63],
[26],
[65],
[44],
[19],
[24],
[86],
[ 2]])
(10, 1)
Out[54]:
where
The numpy.where() function returns the indices of elements in an input array where the
given condition is satisfied.
In [56]: v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[56]:
In [57]: np.where(v>30)
# it will find all the indices here v is greater than 30
In [60]: v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[60]:
array(['hi', 'hi', 'hi', '26', 'hi', 'hi', '19', '24', 'hi', '2'],
Out[62]:
dtype='<U11')
# Output Expalination:
# as v = array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
# here all the values that are grater than 30 are kept as it is
# and those which are not are replaced with 'hello' as the given condition is not sati
Stastics
Cumsum
numpy.cumsum() function is used when we want to compute the cumulative sum of array
elements over a given axis.
In [65]: v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[65]:
In [66]: np.cumsum(v)
array([ 56, 126, 189, 215, 280, 324, 343, 367, 453, 455])
Out[66]:
In [67]: a
array([[ 6, 7, 8],
Out[67]:
[ 9, 10, 11]])
array([[ 6, 7, 8],
Out[70]:
[15, 17, 19]])
In [71]: v.cumprod()
# cumulative product
percentile
numpy.percentile()function used to compute the nth percentile of the given data (array
elements) along the specified axis.
In [72]: v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[72]:
86.0
Out[73]:
In [79]: np.max(v)
86
Out[79]:
2.0
Out[74]:
In [80]: np.min(v)
2
Out[80]:
50.0
Out[75]:
In [76]: np.median(v)
50.0
Out[76]:
45.5
Out[77]:
Flip
The numpy.flip() function reverses the order of array elements along the specified axis,
without disturbing the shape of the array
In [81]: v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[81]:
In [82]: np.flip(v) # reverse
array([ 2, 86, 24, 19, 44, 65, 26, 63, 70, 56])
Out[82]:
In [83]: a
array([[ 6, 7, 8],
Out[83]:
[ 9, 10, 11]])
array([[ 8, 7, 6],
Out[86]:
[11, 10, 9]])
Put
The numpy.put() function replaces specific elements of an array with given values of
p_array. Array indexed works on flattened array.
In [87]: v
array([56, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[87]:
array([20, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[89]:
delet
The numpy.delete() function returns a new array with the deletion of sub-arrays along with
the mentioned axis.
In [90]: v
array([20, 70, 63, 26, 65, 44, 19, 24, 86, 2])
Out[90]:
Plotting Graph
In [109… # plotting 2D plot
# x = y
x = np.linspace(-10,10,100)
x
In [110… # axis x = y
y = x
In [111… y
array([-10. , -9.7979798 , -9.5959596 , -9.39393939,
Out[111]:
-9.19191919, -8.98989899, -8.78787879, -8.58585859,
-8.38383838, -8.18181818, -7.97979798, -7.77777778,
-7.57575758, -7.37373737, -7.17171717, -6.96969697,
-6.76767677, -6.56565657, -6.36363636, -6.16161616,
-5.95959596, -5.75757576, -5.55555556, -5.35353535,
-5.15151515, -4.94949495, -4.74747475, -4.54545455,
-4.34343434, -4.14141414, -3.93939394, -3.73737374,
-3.53535354, -3.33333333, -3.13131313, -2.92929293,
-2.72727273, -2.52525253, -2.32323232, -2.12121212,
-1.91919192, -1.71717172, -1.51515152, -1.31313131,
-1.11111111, -0.90909091, -0.70707071, -0.50505051,
-0.3030303 , -0.1010101 , 0.1010101 , 0.3030303 ,
0.50505051, 0.70707071, 0.90909091, 1.11111111,
1.31313131, 1.51515152, 1.71717172, 1.91919192,
2.12121212, 2.32323232, 2.52525253, 2.72727273,
2.92929293, 3.13131313, 3.33333333, 3.53535354,
3.73737374, 3.93939394, 4.14141414, 4.34343434,
4.54545455, 4.74747475, 4.94949495, 5.15151515,
5.35353535, 5.55555556, 5.75757576, 5.95959596,
6.16161616, 6.36363636, 6.56565657, 6.76767677,
6.96969697, 7.17171717, 7.37373737, 7.57575758,
7.77777778, 7.97979798, 8.18181818, 8.38383838,
8.58585859, 8.78787879, 8.98989899, 9.19191919,
9.39393939, 9.5959596 , 9.7979798 , 10. ])
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x21e80027a30>]
Out[112]:
In [113… y = x**2
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x21e800a7ee0>]
Out[113]:
In [114… # sin(x)
y = np.sin(x)
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x21e80272cb0>]
Out[114]:
In [115… # log
y = np.log(x)
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x21e804679d0>]
Out[119]:
In [ ]: