Numpy
Numpy
Numpy
Numpy
Numpy is an python library We call it a python library because it supports python syntax.
It stands for numerical python.
Numpy is used to perform advance numerical computations on large data sets.
By using, Numpy we can perform complex operations with less line of code.
Numpy provides very useful Data-structure known as Array.
[1 2 3 4 5] <class 'numpy.ndarray'>
In [12]: lavish
np.array is a function in the numpy library that creates an array object. It is used to create
arrays of any dimension and data type. The numpy library is optimized for numerical
operations and provides a large number of functions for mathematical operations on arrays.
On the other hand, np.anything is not a valid function in the numpy library. If you meant to
ask whether you can use other functions in the numpy library instead of np.array, the answer
is yes. The choice of function depends on the specific task you are trying to accomplish. For
example, if you want to create an array of zeros, you can use the np.zeros function 1.
NumPy is a famous Python library used for working with arrays. One of the important
functions of this library is stack ().
NumPy is a library for the Python programming language, adding support for large, multi-
dimensional arrays and matrices, along with a large collection of high-level mathematical
functions…
NumPy is a famous Python library used for working with arrays. One of the important
functions of this library is stack ().
NumPy was created based on the Numeric code. The Numeric code was rewritten to be
easier to maintain, and new features could be added to the library.
Most of the math functions have the same name in NumPy, so we can easily switch from
the non-vectorized functions from Python’s math module to NumPy’s versions.
A- Faster execution
B- Ease of use
C- Compatibility with other libraries
D- Availability of documentation
In [18]: a = np.array([1,2,3,"45"])
a
In [4]: np.__version__
'1.24.3'
Out[4]:
ARRAY :
It is an collection of Homogenous data.
Example : np.array([1,2,3,4,5])
As you can see all are in integer datatype.
[1 2 3 4 5 6 7 8] <class 'numpy.ndarray'>
LISTS VS ARRAY :
With array we can perform some operations which we can't perform with lists.
Array are way faster than list.
With list if we have to print a range or make changes in the range then we have to write
whole line of code.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [31]: print(lst*5)
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[28]:
In [29]: arr*5
array([ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
Out[29]:
As you can see the differences in upper codes like in list we cannot multiply *5 doesn't get
the multiplication elements but if you see with array we don't even have to mention print
function with it.
In [32]: arr*8
array([ 8, 16, 24, 32, 40, 48, 56, 64, 72, 80])
Out[32]:
endTime = time.time()
print(ActaulTime)
0.14682960510253906
arr = np.array(100000)
endTime = time.time()
print(ActaulTime)
Array upcasting :
We can store heterogenous elements in array by using array upcasting.
array upcasting converts all the heterogenous elements in 1 data type this is known as array
upcasting.
array([1, 2, 3, 4, 5])
Out[38]:
By using dtype = 'object' We can make array with heterogenous data elements as you can
see in above code.
In [44]: arr.dtype
np.arange()
It creates an array of numbers.
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[46]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[47]:
np.linspace()
It creates an array of equally spaced values within the range of values.
Syntax -
By default, in linspace both the start and stop values are included
By default, linspace will return the answer in float
As you can see start value is 2 and stop value is 5 by which in the range of 2,5 We need 4
values within it.
np.zeros()
It will return an array of the given shape with all the elements of the array as zero.
Syntax
np.zeros((rows,columns))
In [76]: np.zeros((3,3))
In [77]: np.zeros((3,4))
[[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]])
np.ones()
It will return an array of the given shape with all the elements of the array as 1
Syntax
np.ones((rows , columns))
In [81]: np.ones((3,3))
In [82]: np.ones((3,4))
array([[[1, 1, 1, 1, 1, 1],
Out[83]:
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]]])
np.full()
It will return an array of the given shape with all the elements of the array as value you have
entered.
Syntax
AS you can see in above code np.full is used for creating an specific numbers array as you can
first we have to give rows and columns and then value we have to put it in.
np.eye()
It will return an identity matrix
In an identity matrix, the diagonal elements are 1's and the non diagonal elements are 0's
By default, the values will be in float
Syntax :
np.eye(rows , columns)
In [85]: np.eye(4,4)
array([[0, 0, 0, 0],
Out[93]:
[0, 0, 0, 0],
[0, 0, 0, 0]])
As you can see in upper code I've given 3 values it is giving all in 0's not giving diagonals of
1's in it.
array([[1, 0, 0, 0],
Out[91]:
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
np.zeros_like()
It returns an array of 0's of the given shape of another array
array([[1, 2, 3, 4],
Out[3]:
[2, 3, 4, 5],
[5, 6, 7, 8]])
In [5]: np.zeros_like(arr)
array([[0, 0, 0, 0],
Out[5]:
[0, 0, 0, 0],
[0, 0, 0, 0]])
np.ones_like()
It returns an array of 1's of the given shape of another array
In [113… arr
array([[1, 2, 3, 4],
Out[113]:
[2, 3, 4, 5],
[5, 6, 7, 8]])
In [114… np.ones_like(arr)
array([[1, 1, 1, 1],
Out[114]:
[1, 1, 1, 1],
[1, 1, 1, 1]])
np.full_like()
It will return an array of the given shape with all the elements of the array as value you have
entered.
In [134… arr
np.diagonal()
It returns an array diagonal principal from an array.
By default , function value of offset = 0
array([ 24, 96, 25, 34, 103, 33, 28, 31, 71, 86, 101, 33, 9,
Out[126]:
19, 100, 43, 71, 87, 19, 85, 82, 7, 4, 45, 63])
In [128… np.diagonal(arr)
np.diag()
It creates an diagonal array.
In a diagonal array, the diagonal elements are non-zero rest every element is zero
Syntax:-
np.diag([diagonal])
array([[1, 0, 0, 0, 0],
Out[141]:
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]])
In [139… arr1.T
array([[1, 0, 0, 0, 0],
Out[139]:
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]])
array([1, 7])
Out[142]:
In [143… arr2.T
array([1, 7])
Out[143]:
array([1, 5, 9])
Out[144]:
In [145… arr3.T
array([1, 5, 9])
Out[145]:
In [23]: np.random.seed(1)
arr1 = np.random.randint(1,50,16)
print(arr1)
print("--------------------------------------------------------------------------")
print(arr1.reshape(4,4))
[38 44 13 9 10 12 6 16 1 17 2 13 8 46 7 26]
--------------------------------------------------------------------------
[[38 44 13 9]
[10 12 6 16]
[ 1 17 2 13]
[ 8 46 7 26]]
random.seed() function use for seeding the value at one time only because random.randint
gives new values every time you run the cell so it is used to stop that regular changingvalues.
In [3]: a = np.random.randint(1,20,16)
a
In [5]: np.diagonal(numpyyy)
array([16, 1, 8, 5])
Out[5]:
[16 1 8 5]
[14 5 13]
[ 7 14 1]
[2 5]
[19 3]
In [7]: np.diag(numpyyy)
array([16, 1, 8, 5])
Out[7]:
In [8]: x = np.arange(9).reshape(3,3)
x
In [9]: print(np.diag(x))
print(np.diag(x, k=1))
print(np.diag(x, k=-1))
[0 4 8]
[1 5]
[3 7]
np.trace()
It gives the sum of diagonals of array.
In [10]: numpyyy
In [11]: np.trace(numpyyy)
30
Out[11]:
In [12]: 19+15+1+2
37
Out[12]:
In [13]: np.trace(numpyyy,offset=1)
32
Out[13]:
In [14]: 6+19+14
39
Out[14]:
In [15]: #As you can see it gives values between 0 and 1 whichever value you entered.
np.random.rand(2)
array([0.06796111, 0.86749409])
Out[15]:
In [16]: np.random.randn(21)
In [50]: np.random.random_integers(1,22)
C:\Users\hp\AppData\Local\Temp\ipykernel_7640\3284952165.py:1: DeprecationWarning: Th
is function is deprecated. Please call randint(1, 22 + 1) instead
np.random.random_integers(1,22)
8
Out[50]:
Attributes Description
shape()
This tell us about the shape of array.
It tells us about the columns and rows. first it will tell about the columns then rows.
array([18, 19, 2, 21, 11, 1, 8, 1, 20, 18, 15, 14, 21, 21, 12, 7, 14,
Out[54]:
16, 10, 3])
In [55]: arr1.shape
(20,)
Out[55]:
In [17]: numpyyy
In [57]: numpyyy.shape
(4, 4)
Out[57]:
In [23]: a
In [24]: print(a.shape)
print(a.itemsize)
print(a.data)
(16,)
4
<memory at 0x0000026E45289180>
In [21]: numpyyy.itemsize
In [19]: numpyyy.data
<memory at 0x0000026E45A6CA00>
Out[19]:
As you can see in upper codes it is giving columns first then rows
Reshape
It reshapes the array as per the shape we have passed
It return a new array of the given shape, it doesnot make the changes in the existing array
In [27]: a
In [28]: a.reshape(2,2,4)
In [29]: a.reshape(4,2,2)
array([[[16, 14],
Out[29]:
[ 2, 9]],
[[ 7, 1],
[ 5, 5]],
[[19, 14],
[ 8, 13]],
[[10, 3],
[ 1, 5]]])
In [30]: a.itemsize
4
Out[30]:
In [7]: np.size(a)
16
Out[7]:
dtype()
In [64]: numpyyy
In [65]: numpyyy.dtype
dtype('int32')
Out[65]:
In [66]: a
array([19, 6, 19, 12, 11, 15, 19, 5, 10, 18, 1, 14, 10, 10, 8, 2])
Out[66]:
In [67]: a.dtype
dtype('int32')
Out[67]:
In [73]: b.dtype
dtype('<U6')
Out[73]:
In [75]: b.dtype
dtype('O')
Out[75]:
ndim() - Dimensionality
It tell us about the dimensions of array.
In [76]: a
array([19, 6, 19, 12, 11, 15, 19, 5, 10, 18, 1, 14, 10, 10, 8, 2])
Out[76]:
In [77]: a.ndim
In [78]: numpyyy
In [79]: numpyyy.ndim
2
Out[79]:
In [80]: b
In [82]: b.ndim
2
Out[82]:
array([[[ 1, 2, 3, 4],
Out[91]:
[ 5, 6, 7, 8],
[ 2, 3, 4, 5],
[56, 6, 7, 8]]])
In [92]: arr1.ndim
3
Out[92]:
In [96]: num.ndim
2
Out[96]:
[[18, 5, 1, 15],
[18, 36, 18, 29],
[23, 39, 11, 14]]])
In [98]: num1.ndim
3
Out[98]:
array([[[[37, 17],
Out[104]:
[31, 21],
[36, 18]],
[[ 3, 22],
[30, 37],
[17, 28]],
[[ 9, 29],
[ 3, 36],
[14, 37]]],
[[[37, 19],
[34, 39],
[26, 38]],
[[ 3, 35],
[29, 15],
[12, 27]],
[[22, 17],
[29, 38],
[12, 23]]]])
In [105… num2.ndim
4
Out[105]:
array([[1, 2, 3, 4, 5],
Out[107]:
[7, 8, 9, 0, 2]])
In [111… arr.ndim
2
Out[111]:
array([[[1, 2, 3, 4],
Out[115]:
[2, 3, 4, 5]],
[[3, 4, 5, 6],
[5, 6, 7, 8]]])
In [116… arr1.ndim
3
Out[116]:
Indexing
Fetching the elements out form a particular position or index
Syntax:
arr[index]
In [167… numpyyy
In [166… print(numpyyy[0])
print(numpyyy[1])
print(numpyyy[-1])
print(numpyyy[-2])
print(numpyyy[0][0])
print(numpyyy[-1][-1])
print(numpyyy[len(numpyyy)-1])
print(numpyyy[len(numpyyy)-1][-2])
print(numpyyy[2][3])
print(numpyyy[2][0])
In [169… numpyyy[2,0] = 55
In [170… numpyyy
In [161… np.random.seed(1)
arr1 = np.random.randint(1,50,24)
arr1
array([38, 44, 13, 9, 10, 12, 6, 16, 1, 17, 2, 13, 8, 46, 7, 26, 21,
Out[161]:
38, 19, 21, 12, 43, 29, 30])
In [163… arr.ndim
2
Out[163]:
In [168… len(arr)
4
Out[168]:
In [171… arr
In [172… arr[1,4]
2
Out[172]:
Slicing :
rows Slicing :
Columns Slicing :
variable[column_startindex : column_endingindex : step_size]
step_size = 0
In [173… arr
In [177… print(arr[0])
print("----------------------")
print(arr[-1])
print("----------------------")
print(arr[::1])
print("----------------------")
print(arr[::-1])
[38 44 13 9 10 12]
----------------------
[19 21 12 43 29 30]
----------------------
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[19 21 12 43 29 30]
[ 8 46 7 26 21 38]
[ 6 16 1 17 2 13]
[38 44 13 9 10 12]]
In [180… print(arr[0:2:])
print("----------------------")
print(arr[:len(arr):])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]]
----------------------
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
In [190… print(arr[::,::])
print("----------------------")
print(arr[1:3:,::])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]]
In [187… print(arr[:2:,:5:])
print("----------------------")
print(arr[:2:,:1:])
[[38 44 13 9 10]
[ 6 16 1 17 2]]
----------------------
[[38]
[ 6]]
In [193… print(arr[::,::])
print("----------------------")
print(arr[2:4:,2:-1:])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 7 26 21]
[12 43 29]]
In [194… print(arr[::,::])
print("----------------------")
print(arr[2::,:2:])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 8 46]
[19 21]]
In [195… print(arr[::,::])
print("----------------------")
print(arr[1::,2:3:])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[ 1]
[ 7]
[12]]
In [196… print(arr[::,::])
print("----------------------")
localhost:8888/doc/tree/OneDrive/Desktop/PYTHON'S FILES/NUMPY.ipynb 22/80
1/13/24, 10:51 AM NUMPY
print(arr[::,5::])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[12]
[13]
[38]
[30]]
In [200… print(arr[::,::])
print("----------------------")
print(arr[::-1,5:len(arr):-1])
[[38 44 13 9 10 12]
[ 6 16 1 17 2 13]
[ 8 46 7 26 21 38]
[19 21 12 43 29 30]]
----------------------
[[30]
[38]
[13]
[12]]
In [201… np.random.seed(1)
arr2 = np.random.randint(22,222,81).reshape(9,9)
arr2
array([[ 59, 162, 94, 159, 155, 101, 214, 166, 151],
Out[201]:
[ 93, 156, 47, 200, 42, 123, 168, 161, 178],
[179, 164, 72, 90, 118, 108, 163, 159, 29],
[ 85, 83, 44, 79, 23, 150, 82, 30, 163],
[137, 197, 143, 52, 93, 153, 220, 171, 71],
[ 79, 25, 218, 46, 65, 98, 48, 74, 102],
[131, 137, 63, 37, 86, 218, 47, 133, 157],
[ 48, 175, 126, 44, 31, 217, 148, 45, 147],
[122, 177, 187, 79, 105, 188, 158, 54, 184]])
In [205… print(arr2[::,::])
print("----------------------")
print(arr2[:: ,8:len(arr2):])
In [207… print(arr2[::,::])
print("--------------------------------------------------------")
print(arr2[::-1,8:len(arr2):])
In [215… print(arr2[::,::])
print("----------------------------------------------")
print(arr2[::-1,4:5:])
In [217… print(arr2[::,::])
print("----------------------------------------------")
print(arr2[::,6:7:])
In [233… print(arr2[::,::])
print("----------------------------------------------")
print(np.diagonal(arr2)[::])
print("----------------------------------------------")
print(np.diagonal(arr2)[::-1])
print("----------------------------------------------")
print(np.diagonal(arr2, offset=1)[::])
print("----------------------------------------------")
print(np.diagonal(arr2, offset=-1)[::])
print("----------------------------------------------")
print(np.diag(arr2 , k=6)[::])
print("----------------------------------------------")
print(np.diagonal(arr2 , offset=8)[::])
You're on the right track – np.diagonals is well suited for this, but you need to take care
computing the offsets. In numpy (and in matrix math by convention) the diagonals run {{top-
left to bottom-right.}} The main diagonal has offset 0; the diagonals above this have positive
offsets, and the diagonals below have negative offsets.
In [234… arr2
array([[ 59, 162, 94, 159, 155, 101, 214, 166, 151],
Out[234]:
[ 93, 156, 47, 200, 42, 123, 168, 161, 178],
[179, 164, 72, 90, 118, 108, 163, 159, 29],
[ 85, 83, 44, 79, 23, 150, 82, 30, 163],
[137, 197, 143, 52, 93, 153, 220, 171, 71],
[ 79, 25, 218, 46, 65, 98, 48, 74, 102],
[131, 137, 63, 37, 86, 218, 47, 133, 157],
[ 48, 175, 126, 44, 31, 217, 148, 45, 147],
[122, 177, 187, 79, 105, 188, 158, 54, 184]])
In [235… np.diag(arr2)
array([ 59, 156, 72, 79, 93, 98, 47, 45, 184])
Out[235]:
In [236… np.diag(np.diag(arr2))
In [4]: np.diag(np.diag(arr1))
array([[47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
Out[4]:
[ 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 63, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 56, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33]])
In [6]: arr1
array([[60, 66, 69, 63, 45, 61, 49, 45, 69, 31, 67],
Out[6]:
[64, 50, 64, 53, 69, 44, 56, 45, 56, 58, 50],
[32, 34, 45, 36, 59, 55, 66, 45, 59, 69, 64],
[52, 59, 66, 41, 31, 43, 41, 50, 69, 53, 46],
[65, 35, 56, 62, 51, 37, 45, 61, 59, 42, 46],
[61, 59, 69, 59, 34, 38, 53, 49, 48, 63, 59],
[59, 38, 69, 57, 69, 49, 45, 64, 41, 49, 55],
[36, 69, 34, 35, 51, 33, 67, 58, 62, 50, 40],
[46, 62, 54, 32, 37, 58, 37, 34, 42, 54, 54],
[30, 31, 44, 32, 64, 44, 33, 41, 62, 31, 48],
[57, 44, 54, 33, 32, 66, 49, 67, 36, 41, 47]])
In [8]: np.diagflat(np.diagflat(arr1))
diagflat() :
It creates the diagonals from given array and rest of non diagonal values becomes 0's.
In [12]: numm.ndim
2
Out[12]:
In [19]: x = np.diagflat([[[12,12],[22,22],
[33,33],[44,44]]])
x
array([[12, 0, 0, 0, 0, 0, 0, 0],
Out[19]:
[ 0, 12, 0, 0, 0, 0, 0, 0],
[ 0, 0, 22, 0, 0, 0, 0, 0],
[ 0, 0, 0, 22, 0, 0, 0, 0],
[ 0, 0, 0, 0, 33, 0, 0, 0],
[ 0, 0, 0, 0, 0, 33, 0, 0],
[ 0, 0, 0, 0, 0, 0, 44, 0],
[ 0, 0, 0, 0, 0, 0, 0, 44]])
In [20]: x.ndim
2
Out[20]:
In [21]: x = np.diagonal([[[12,12],[22,22],
[33,33],[44,44]]])
x
array([[12],
Out[21]:
[12]])
In [24]: x = np.diag([[[12,12],[22,22],
[33,33],[44,44]]])
x
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[24], line 1
----> 1 x = np.diag([[[12,12],[22,22],
2 [33,33],[44,44]]])
3 x
As you can see in above codes np.diag and np.diagonal doesn't create a array
by giving arrays it is only applicable in np.diagflat
In [29]: np.random.seed(6)
arr3 = np.random.randint(1,200,64).reshape(8,8)
arr3
np.random.seed(1)
arr1 = np.random.randint(30,70,48).reshape(3,4,4)
arr1
In [7]: arr1[0]
In [8]: arr1[0,2] = 22
In [9]: arr1
In [15]: arr1
Slicing :
Syntax :
layer_startindex = 0
In [16]: arr1
In [17]: arr1[:len(arr1):2]
In [18]: arr1[::]
In [19]: arr1[::-1]
Now,
In [20]: arr1
In [32]: arr1[2,2]
In [37]: arr1
[[[41 35 45 30]]]
----------------------------------------------
[[[22 11 12 22]]
[[73 33 36 63]]]
----------------------------------------------
[[[41 35 45 30]
[22 11 12 22]]
[[54 43 38 60]
[73 33 36 63]]]
----------------------------------------------
[[[22 11 12 22]
[41 35 45 30]]
[[73 33 36 63]
[54 43 38 60]]]
[[[36 55 50 67]
[41 35 45 30]]
[[43 39 37 52]
[59 44 34 53]]
[[33 34 54 42]
[54 43 38 60]]]
[[[36 55 50 67]
[67 42 38 39]]
[[43 39 37 52]
[48 50 41 58]]
[[33 34 54 42]
[31 30 47 38]]]
[[[36 55 50 67]]
[[43 39 37 52]]
[[33 34 54 42]]]
Now,
arr[layer_startindex : layer_endindex : step_size , row_startindex :
row_endindex : step_size , column_startindex : column_endindex : step_size]
startindex = 0
In [48]: arr1
[[58]
[53]
[25]
[52]]
[[38]
[60]
[63]
[42]]]
[[[39]
[30]]
[[38]
[60]]]
[[[11 12]
[55 50]]
[[60 26]
[39 37]]]
[[[11 12]
[55 50]]
[[33 36]
[34 54]]]
In [57]: np.random.seed(1)
varr = np.random.randint(22,172,49).reshape(7,7)
varr
In [58]: np.diag(varr)
In [60]: np.diag(varr)[::-1]
Now Now Now, You can see in Below code that in diagonal it is possible that
we can extract the diagonal from {right-top-left-bottom}
In [66]: np.diag(varr[::-1])[::]
In [67]: np.diag(varr[::-1])[::-1]
Syntax:
np.random.random(number of values)
In [69]: x = np.random.random(24)
x
In [70]: i = np.random.random(36).reshape(3,4,3)
i
random.randint()
It returns a 1-D array of random numbers (integers) between a specified range
Synatx:
By default, both the start and the stop values are excluded
In [71]: v = np.random.randint(1,22,16).reshape(4,4)
v
random.seed(random state)
It is used to set the random state of the randomized value
Random state is an integer number in the range 0 to (2**32)-1
In [72]: np.random.seed(10)
arrr = np.random.randint(0,51,36).reshape(6,6)
arrr
In [74]: np.random.seed(10)
arr1 = np.random.rand(6,6)
arr1
In [75]: (2**32)-1
4294967295
Out[75]:
random.normal()
It returns an array of random value those are normally distributed
Functions in Array
np.sum()
It returns the sum of the array.
Syntax :
np.sum(arr , axis = 0)
arr.sum(axis = 0,1)
axis = 0 ------> Interpreter reads the array from top to bottom which known as row
wise operation.
axis = 1 ------> Interpreter reads the array from left to right which known as column
wise operation.
In [83]: np.random.seed(1)
axxxiiss = np.random.randint(1,22,14)
axxxiiss
139
Out[84]:
In [87]: axxxiiss.sum()
139
Out[87]:
In [86]: axxxiiss.sum(axis = 1)
---------------------------------------------------------------------------
AxisError Traceback (most recent call last)
Cell In[86], line 1
----> 1 axxxiiss.sum(axis = 1)
As you can see in upper code is giving error by out of bound for array of 1-D ,
In [97]: np.random.seed(1)
i_ = np.random.randint(0,51,16).reshape(4,4)
i_
In [104… i_.sum(axis = 1)
np.mean()
It returns the average (mean) of the array
Syntax:
In [106… np.random.seed(1)
arr = np.random.randint(1,51,36).reshape(6,6)
arr
In [107… np.mean(arr)
22.055555555555557
Out[107]:
In [109… (38+ 44 + 13 + 9 + 10 + 12 + 6 + 16 + 1 + 17 + 2 + 13 + 8 + 46 + 7
+ 26 + 21 + 38 + 19 + 21 + 12 + 43 + 29 + 30 + 15 + 5 + 24 + 24 + 42 + 50 + 31 + 33 +
22.055555555555557
Out[109]:
To Calculate mean,
np.median()
It return the median of an array
Syntax:
In [116… arr
np.var()
It return the variance of the array
Syntax:
np.random.seed(1)
x = np.random.randint(1,51,16).reshape(4,4)
x
In [4]: x.var()
In [7]: np.mean(x)
16.75
Out[7]:
199.1875
Out[9]:
231.5
Out[11]:
np.std()
It returns the standard deviation of an array
Syntax:
In [8]: np.random.seed(1)
axisss = np.random.randint(1,30,25).reshape(5,5)
axisss
print(v)
print(c)
Solving of Variances
34.160000000000004
Out[16]:
In [14]: math.sqrt(34.16)
5.844655678480983
Out[14]:
2. After that from mean we have to find the variance(np.var()) of the array of
axis(0,1)
In [5]: np.random.seed(1)
garryy = np.random.randint(1,22,25).reshape(5,5)
garryy
In [18]: print(np.mean(garryy))
print(np.var(garryy))
print(np.std(garryy))
11.76
31.862399999999997
5.644678910265844
In [19]: math.sqrt(31.862399999999997)
5.644678910265844
Out[19]:
np.min()
It return the minimum value of the arary
Syntax:
In [20]: garryy
In [21]: np.min(garryy)
1
Out[21]:
As you can see in below it shows that by finding np.min() we find minimum value and it
checks the all the axis of 0 (rows) of the array and give each value from each row specifically
minimum value.
array([2, 6, 6, 1, 5])
Out[22]:
array([6, 1, 2, 6, 5])
Out[23]:
np.max()
It return the maximum value of the arary
Syntax:
In [24]: garryy
In [25]: np.max(garryy)
21
Out[25]:
As you can see in below it shows that by finding np.max() we find maximum value and it
checks the all the axis of 0 (rows) of the array and give each value from each row specifically
np.percentile()
It return the specified percentile value of the array
In [6]: garryy
5.4
Out[32]:
5.4
In [36]: len(garryy)
5
Out[36]:
In [33]: np.percentile(garryy , 7)
4.040000000000001
Out[33]:
In [53]: a = garryy.flatten()
a
array([ 6, 12, 13, 9, 10, 12, 6, 16, 1, 17, 2, 13, 8, 14, 7, 19, 21,
Out[53]:
6, 19, 21, 12, 11, 15, 19, 5])
In [54]: np.sort(a)
astype() :
In [21]: arr1.astype(int)
In [22]: arr1.astype(complex)
In [23]: arr1.astype(str)
In [25]: arr1.astype(float)
In [26]: arr1.astype(bool)
In [27]: arr1.astype(list)
In [28]: arr1.astype(set)
In [29]: a = None
print(a , type(a))
In [31]: arr1.dtype
dtype('float64')
Out[31]:
As you can see now by default array is in float data type. because of np.nan
In [33]: arr2.dtype
dtype('float64')
Out[33]:
np.isnan()
It checks for nan values and returns a boolean array, where True means the null value is
present and False means the non-null values is present
In [34]: arr2
In [35]: np.isnan(arr2)
Count the null values and Non null values inside the array
Syntax :
In [37]: arr2
In [38]: np.isnan(arr2)
In [36]: np.isnan(arr2).sum()
3
Out[36]:
In [65]: (~np.isnan(arr2)).sum()
6
Out[65]:
6
Out[68]:
6
Out[70]:
np.where(condition)
np.where(condition)
To fetch the element we pass np.where () as the index to the array object
In [39]: arr2
In [40]: np.where(np.isnan(arr2))
As you can see in above code that it is returning two arrays first tarray tells us about the
layers or lists in the array by indexing numbers and the another array states the position
where nan values are there.
As you can see at 0th list --- at 2nd position there is an nan value.
In [41]: np.random.seed(1)
arr3 = np.random.randint(1,51,36).reshape(4,9)
arr3
In [44]: np.random.seed(45)
arr = np.random.randint(10,100,12).reshape(3,2,2)
arr
array([[[85, 40],
Out[44]:
[13, 42]],
[[71, 95],
[45, 78]],
[[25, 75],
[24, 63]]])
[[ True, True],
[False, True]],
[[False, True],
[False, True]]])
In [33]: np.where(np.isnan(arr7))
In [34]: arr7[np.where(np.isnan(arr7))]
array([[[85, 40],
Out[56]:
[13, 42]],
[[71, 95],
[45, 78]],
[[25, 75],
[24, 63]]])
array([85, 40, 42, 71, 95, 45, 78, 25, 75, 24, 63])
Out[71]:
array([85, 40, 42, 71, 95, 45, 78, 25, 75, 24, 63])
Out[62]:
In [74]: np.random.seed(10)
arr2 = np.random.randint(1,51,36).reshape(6,6)
arr2
np.where -- Case 3
Syntax : - np.where(condition, x, arr)
If the condition is True, then x is the result, otherwise the value remains the same
In [78]: arr2
In [37]: arr7[np.isnan(arr7)] = 1
In [41]: arr7
In [40]: arr7.astype(int)
arr[np.isnan(arr)] = arr(~np.isnan(arr)).mean()
By mean
In [42]: arr = np.array([10,20,30, np.nan, 50, np.nan, 45, 60, np.nan, np.nan, 78, 62]).reshape
arr
In [43]: arr.mean()
nan
Out[43]:
44.375
Out[44]:
In [46]: arr
In [48]: a.mean()
nan
Out[48]:
15.5
Out[49]:
In [62]: a[np.isnan(a)] = y
In [63]: a
array([[ 1. , 2. , 3. ],
Out[63]:
[15.5, 5. , 6. ],
[15.5, 15.5, 76. ]])
By Median
In [65]: a
In [67]: np.median(a)
nan
Out[67]:
In [72]: np.median(m)
4.0
Out[72]:
In [74]: a
In [77]: np.mean(z)
nan
Out[77]:
48.0
Out[79]:
In [82]: z
In [84]: np.median(b)
nan
Out[84]:
45.0
Out[90]:
In [92]: b
In [93]: b.astype(int)
In [96]: print(arr.mean())
print("----------------------------------------------------------")
w = arr1[np.isnan(arr1) == False].mean()
print(w)
print("----------------------------------------------------------")
arr1[np.isnan(arr1)] = w
print(arr1)
44.375
----------------------------------------------------------
54.5
----------------------------------------------------------
[[54.5 32. 23. ]
[54.5 54.5 54.5]
[76. 87. 54.5]]
In [98]: print(np.median(arr9))
print("-------------------------------------------------------")
qqq = arr9[np.isnan(arr9) == False]
x = np.median(qqq)
print(x)
print("-------------------------------------------------------")
arr9[np.isnan(arr9)] = x
print(arr9)
nan
-------------------------------------------------------
449.5
-------------------------------------------------------
[[449.5 101. 223. ]
[449.5 449.5 449.5]
[676. 787. 449.5]]
In [122… arr9 = np.array([np.nan , 101 , 223 , np.nan , np.nan , np.nan , 676 , 787 , np.nan]).
arr9
As you can see in below code , I've replaced non null values with 22 and null values with
zero(0)
In [124… arr9
In [126… arr9.astype(int)
np.argwhere()
It returns an array object that contains the indexes of all the non zero element from the
array
Syntax:
np.argwhere(arr)
In [127… arr9
In [128… np.argwhere(arr9)
array([[0, 1],
Out[128]:
[0, 2],
[2, 0],
[2, 1]], dtype=int64)
In [129… arr1
In [130… np.argwhere(arr1)
array([[0, 0],
Out[130]:
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[2, 2]], dtype=int64)
As you can see that in this array there is no zero elements so it giving all the indexes
[ 1 2 3 4 5 0 0 78 9 0 7 89 0 222 0]
-------------------------------------------------------------------
Non - Zero elements Indexes : [[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 7]
[ 8]
[10]
[11]
[13]]
-------------------------------------------------------------------
Zero Elements Indexes : [[ 5]
[ 6]
[ 9]
[12]
[14]]
As you can see we can see the indexes of zero elements also by giving conditions in it.
np.argmax()
It returns the index of the maximum number
In case of multiple maximum number, it will return the index of the first maximum number
It treats the n-d array as 1-D array
In [147… arr1
In [148… np.argmax(arr1)
7
Out[148]:
As you can see , it is giving index 7th of the arr1 which is 87 . as you can see it treats the array
ino 1D array.
np.argmin()
It returns the index of the minimum number
In case of multiple minimum number, it will return the index of the first minimum number
It treats the n-d array as 1-D array
In [149… arr1
In [150… np.argmin(arr1)
2
Out[150]:
As you can see , it is giving index 2nd of the arr1 which is 23 . as you can see it treats the
array ino 1D array.
cap the value of the above the above array between the range 40 -70
any value less than 40-->40 || any value greater than 70 --->70
In [178… np.random.seed(1)
arrg2 = np.random.randint(100,510,36).reshape(6,6)
arrg2
cap the value of the above the above array between the range 250
any value less than 250-->"Less Than 250" || any value greater than 250 --->"Greater than
250"
In [179… strr_ = np.where(arrg2 > 250 , "Greater than 250", np.where(arrg < 250 , "Less than 25
strr_.astype(str)
np.clip()
It is used to clipping the value between lower limit to upper limit.
Syntax
In [206… arrg
In [209… arrg2
In [5]: np.random.seed(7)
arr = np.random.randint(1,51,36).reshape(6,6)
arr
In [6]: np.diag(arr)
In [7]: np.diag(np.diag(arr))
array([[48, 0, 0, 0, 0, 0],
Out[7]:
[ 0, 29, 0, 0, 0, 0],
[ 0, 0, 27, 0, 0, 0],
[ 0, 0, 0, 45, 0, 0],
[ 0, 0, 0, 0, 25, 0],
[ 0, 0, 0, 0, 0, 5]])
In [8]: arr
In [10]: print(np.mean(arr))
print(np.var(arr))
print(np.std(arr))
23.666666666666668
253.16666666666666
15.911211979816832
15.911211979816832
Out[11]:
In [12]: np.median(arr)
24.0
Out[12]:
40.2
Out[17]:
In [20]: arr3.astype(int)
In [22]: arr
array([[48],
Out[28]:
[22],
[47],
[ 5],
[ 7],
[ 1]])
arr_name[condition]
In [3]: np.random.seed(12)
arr1 = np.random.randint(22,87,36).reshape(6,6)
arr1
As you can see in below code that it is giving bool values of arrays because we directly put
arr1>25 if we put the same condition inside arr_name then it'll only show the greater
elements of arr1 by 25 you can see in below codes.
In [4]: arr1>25
In [5]: arr1[arr1>25]
array([49, 28, 70, 44, 71, 74, 27, 35, 56, 35, 57, 84, 57, 55, 52, 85, 40,
Out[5]:
72, 28, 67, 52, 54, 49, 81, 81, 47, 78, 26, 66, 59, 75, 75, 69])
In [7]: arr1[arr1<36]
In [14]: df = sns.load_dataset("titanic")
df.head()
Out[14]: survived pclass sex age sibsp parch fare embarked class who adult_male deck
In [16]: # As you can see the filtering in titanic dataset of in sex column of female
df[df["sex"] =="female"]
Out[16]: survived pclass sex age sibsp parch fare embarked class who adult_male de
... ... ... ... ... ... ... ... ... ... ... ...
Out[21]: survived pclass sex age sibsp parch fare embarked class who adult_male dec
... ... ... ... ... ... ... ... ... ... ... ...
91 rows × 15 columns
Out[23]: survived pclass sex age sibsp parch fare embarked class who adult_male dec
... ... ... ... ... ... ... ... ... ... ... ...
74 rows × 15 columns
Array Concatination
Vertical Concatination
Horizontal Concatination
Syntax
In [24]: a = np.arange(24).reshape(4,6)
a
array([[ 0, 1, 2, 3, 4, 5],
Out[24]:
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
In [26]: a.shape
(4, 6)
Out[26]:
In [27]: b = np.arange(6).reshape(1,6)
b
array([[0, 1, 2, 3, 4, 5]])
Out[27]:
array([[ 0, 1, 2, 3, 4, 5],
Out[30]:
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[ 0, 1, 2, 3, 4, 5]])
As you can see in below code that why it's throwing an error because of 1-D array itcan't
concatinate with columns which is axis = 1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[31], line 1
----> 1 np.concatenate((a,b) , axis = 1)
ValueError: all the input array dimensions except for the concatenation axis must mat
ch exactly, but along dimension 0, the array at index 0 has size 4 and the array at i
ndex 1 has size 1
In [32]: a
array([[ 0, 1, 2, 3, 4, 5],
Out[32]:
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
Watch the shape and size of "a" array which is shape(4,6) means 4 rows and 6 columns thats
why now we have to make the another array in that suitable way
In [35]: c = np.arange(4).reshape(4,1)
print(c)
[[0]
[1]
[2]
[3]]
------------------------------------------
[[ 0 1 2 3 4 5 0]
[ 6 7 8 9 10 11 1]
[12 13 14 15 16 17 2]
[18 19 20 21 22 23 3]]
In [42]: arr1+5
In [43]: arr1//3
In [44]: arr1*5
In [45]: arr1%4
array([[1, 0, 0, 1, 2, 0],
Out[45]:
[3, 2, 3, 3, 0, 2],
[3, 1, 0, 1, 3, 0],
[1, 0, 0, 0, 3, 0],
[2, 1, 1, 1, 3, 2],
[2, 2, 3, 3, 3, 1]], dtype=int32)
In [47]: arr1 - 4
As you can see all these arthemetic operations are done over arrays which is basically asked
by the interviewer how these operations are handled by numpy.
Array Broadcasting
NOTE : - Atleast one dimension should be same and the other dimension should be 1 in either
of the array
In [49]: arr1 + 5
In [50]: w = np.arange(24)
w
In [51]: for i in w:
print(i)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
In [52]: arr1
# As you can se that it is only giving lists of arrays in iterating not giving an elem
As you can see it is not giving elements over an iteration so we have a function for that in
numpy which is known as np.nditer()
np.nditer()
It returns an iterable object.
In [57]: arr1
49 28 24 25 70 44 71 74 27 35 56 22 35 57 84 57 55 52 85 40 72 28 67 52 54 49 81 81 4
7 78 26 66 59 75 75 69
Determinant
It is used to find the determinant of the array.
Formula
det=a(ei−fh)−b(di−fg)+c(dh−eg)
Which differs to array like this:
[[a,b,c], [d,e,f],
[g,h,i]
Syntax
np.linalg.det(arr)]]
In [60]: arr1
In [62]: np.linalg.det(arr1)
2266430643.0000033
Out[62]:
array([[0, 1, 2],
Out[69]:
[3, 4, 5],
[6, 7, 8]])
In [70]: np.linalg.det(arr2)
0.0
Out[70]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: