0% found this document useful (0 votes)
5 views

NumPy For Data Science

Uploaded by

Indranil Patra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

NumPy For Data Science

Uploaded by

Indranil Patra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

DATA SCIENCE

Created by :- Sonu Kumar


Created by :- Sonu Kumar

1. NumPy in Python
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
NumPy can be used to perform a wide variety of mathematical operations on arrays.
ItaddspowerfuldatastructurestoPythonthatguaranteeefficientcalculationswitharraysandmatricesand
itsuppliesanenormouslibraryofhigh-levelmathematicalfunctionsthatoperateonthesearraysand
m atrices.
Besidesitsobviousscientificuses,NumPycanalsobeusedasanefficientmulti-dimensionalcontainerof
generic data.
Arbitrarydata-typescanbedefinedusingNumpywhichallowsNumPytoseamlesslyandspeedily
integrate with a wide variety of databases.
TheimportnumpyportionofthecodetellsPythontobringtheNumPylibraryintoyourcurrent
environment.
TheasnpportionofthecodethentellsPythontogiveNumPythealiasofnp.
This allows you to use NumPy functions by simply typing np.
NumPyisaverypopularpythonlibraryforlargemulti-dimensionalarrayandmatrixprocessing,withthe
help of a large collection of high-level mathematical functions.
ItisveryusefulforfundamentalscientificcomputationsinMachineLearning.
NumPy is a module for Python.
The name is an acronym for "Numeric Python" or "Numerical Python".
Itispronounced/'nʌmpai/(NUM-py)orlessoften/'nʌmpi(NUM-pee)). It
is an extension module for Python, mostly written in C.
Anumpyarrayisagridofvalues,allofthesametype,andisindexedbyatupleofnonnegativeintegers.
Thenumberofdimensionsistherankofthearray;theshapeofanarrayisatupleofintegersgivingthe
size of the array along each dimension.
NumPyisageneral-purposelibraryforworkingwithlargearraysandmatrices.
Scrapy is the most popular high-level Python framework for extracting data from websites.
MatplotlibisastandarddatavisualizationlibrarythattogetherwithNumPy,SciPy,andIPythonprovides
features similar to MATLAB.
NumPy(shortforNumericalPython)providesanefficientinterfacetostoreandoperateondensedata
b uf fers.
Insomeways,NumPyarraysarelikePython'sbuilt-inlisttype,butNumPyarraysprovidemuchmore
efficient storage and data operations as the arrays grow larger in size.

NumPy Features
High-performance N-dimensional array object
ItcontainstoolsforintegratingcodefromC/C++andFortran
Itcontainsamultidimensional containerforgenericdata
Additionallinearalgebra,Fouriertransform,andrandomnumbercapabilities
It consists of broadcasting functions
It had data type definition capability to work with varied databases

NumPy Arrays are faster than Python Lists because of the following reasons:
Created by :- Sonu Kumar

Anarrayisacollectionofhomogeneousdata-typesthatarestoredincontiguousmemorylocations.
On the other hand, a list in Python is a collection of heterogeneous data types stored in non-
contiguous memory locations.

ndarray attributes
Every array in NumPy is an object of ndarray class.
The Properties of an array can be manipulated by accessing the ndarray attributes.
Themoreimportantattributesofanndarrayarendarray.ndim,ndarray.shape,ndarray.size,
ndarray.dtype, and ndarray.itemsize

NumPy data types


i-integer
b- boolean
u-unsignedinteger
f-float
c-complexfloat
m-timedelta
M-datetime
O-object
S- string
U - Unicode string
V - fixed chunk of memory for other type
Created by :- Sonu Kumar

import numpy library

In [1]:

1 importnumpyasnp

You can find more information about NumPy when executing the following commands.

In [2]:
1
# help(np)

Some NumPy methods


array()
arange()
zeros()
ones()
empty()
linspace()
Created by :- Sonu Kumar

array()

array(data_type, value_list)

In [3]:
1 numpy_array =np.array([0.577,1.618,2.718, 3.14,6,28, 37,1729])
2 print(numpy_array)
3 print(numpy_array.dtype)

[5.770e-011.618e+002.718e+003.140e+006.000e+002.800e+013.700e+01
1.729e+03]
float64

In [4]:

1 numpy_array= np.array([0.577,1.618,2.718,3.14,6,28,37,1729]).reshape(2,4)
2 print(numpy_array)
3 print(numpy_array.dtype)
4 print()
5 numpy_array= np.array([0.577,1.618,2.718,3.14,6,28,37,1729]).reshape(4,2)
6 print(numpy_array)
7 print(numpy_array.dtype)
8

[[5.770e-011.618e+002.718e+003.140e+00]
[6.000e+00 2.800e+01 3.700e+01 1.729e+03]]
float64
[[5.770e-01
1.618e+00]
[2.718e+00 3.140e+00]
[6.000e+00 2.800e+01]
[3.700e+01 1.729e+03]]
float64
Created by :- Sonu Kumar
The following code gives a TypeError.

In [5]:
1 numpy_array =np.array(0.577,1.618, 2.718,3.14,6,28, 37,1729)
2 #Thiserrorisduetocallingarray()mithmultiplearguments,insteadofasinglelistofvalues
3 print(numpy_array)

------------------------------------------- -------- -------- -------- ------- -


TypeError Traceback(mostrecentcalllast)
~\AppData\Local\Temp/ipykernel_11868/2649635874.py in <module>
----> 1 numpy_array = np.array(0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729) # This error is due to calling a
rray() mith multiple arguments, instead of a single list of values
2 print(numpy_array)

TypeError:array()takesfrom1to2positionalarguments but8weregiven

In[ ]:

1 #Thefollowingcodereturnsasequenceoftwodimensionalarray
2 numpy_array=np.array([(0,1, 1), (2, 3, 5),(8, 13, 21)])
3 print(numpy_array)

[[011]
[2 3 5]
[ 8 13 21]]

In[ ]:

1 #Totransfromdatatypeintocomplexnumber
2 numpy_array =np.array([(0,1, 1),(2, 3, 5), (8, 13,21)],dtype=complex)
3 print(numpy_array)

[[0.+0.j 1.+0.j 1.+0.j]


[2.+0.j 3.+0.j 5.+0.j]
[ 8.+0.j 13.+0.j 21.+0.j]]

arange()

np.arange(start, end, step, dtype)

In[ ]:
1 numpy_array= np.arange(0,100, 5, int)
2 print(numpy_array)
3 print(len(numpy_array))

[05101520253035404550556065707580859095]
20
Created by :- Sonu Kumar
In [6]:

1 numpy_array=np.arange(0,100,5,int)
2 numpy_array.shape=(4,5)
3 print(numpy_array)

[[ 0 5 10 15 20]
[25 30 35 40 45]
[50 55 60 65 70]
[75 80 85 90 95]]

In [7]:

1 numpy_array=np.arange(0,100,5,int).reshape(4,5)
2 print(numpy_array)

[[ 0 5 10 15 20]
[25 30 35 40 45]
[50 55 60 65 70]
[75 80 85 90 95]]

In [8]:

1 #Sinceoneofparametersinthearrayisfloattype,theelementsinthearrayareoftypefloat.
2 numpy_array=np.arange(0,3.14,0.3)
3 print(numpy_array)

[0. 0.30.60.91.21.51.82.12.42.73.]

In [9]:

1 #Typeofarange
2 numpy_array=np.arange(2,37,3)
3 print(numpy_array)
4 print(type(numpy_array))

[2 5 8111417202326293235]
<class 'numpy.ndarray'>

zeros()
np.zeros((shape of the array))

In [10]:

1 numpy_zeros=np.zeros((3,4))
2 print(numpy_zeros)
3 print(type(numpy_zeros))

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
<class 'numpy.ndarray'>
Created by :- Sonu Kumar

In [11]:

1 numpy_zeros=np.zeros((3,4),dtype=int)
2 print(numpy_zeros)
3 print(type(numpy_zeros))

[[0 0 0 0]
[0000]
[0 0 0 0]]
<class 'numpy.ndarray'>

In [12]:

1 numpy_zeros=np.zeros((3,4),dtype=complex)
2 print(numpy_zeros)
3 print(type(numpy_zeros))

[[0.+0.j 0.+0.j 0.+0.j 0.+0.j]


[0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[0.+0.j 0.+0.j 0.+0.j 0.+0.j]]
<class 'numpy.ndarray'>

In [13]:

1 numpy_zeros=np.zeros((3,4),dtype=bool)
2 print(numpy_zeros)
3 print(type(numpy_zeros))

[[False False False False]


[False False False False]
[False False False False]]
<class 'numpy.ndarray'>

ones()

np.ones((shape of the array))

In [14]:
1 numpy_ones=np.ones((3,4))
2 print(numpy_ones)
3 print(type(numpy_ones))

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
<class 'numpy.ndarray'>

In [15]:

1 numpy_ones=np.ones((3,4),dtype=int)
2 print(numpy_ones)
3 print(type(numpy_ones))

[[1 1 1 1]
[1111]
[1 1 1 1]]
<class 'numpy.ndarray'>
Created by :- Sonu Kumar

In [16]:

1 numpy_ones=np.ones((3,4),dtype=complex)
2 print(numpy_ones)
3 print(type(numpy_ones))

[[1.+0.j 1.+0.j 1.+0.j 1.+0.j]


[1.+0.j 1.+0.j 1.+0.j 1.+0.j]
[1.+0.j 1.+0.j 1.+0.j 1.+0.j]]
<class 'numpy.ndarray'>

In [17]:
1 numpy_ones=np.ones((3,4),dtype=bool)
2 print(numpy_ones)
3 print(type(numpy_ones))

[[ True True True True]


[ True True True True]
[True True True True]]
<class 'numpy.ndarray'>

empty()

np.empty((shape of the array))

It creates an empty array in the certain dimension with random values which change for every call.

In [18]:
1 numpy_empty=np.empty((4,4))
2 print(numpy_empty)

[[4.67296746e-307 1.69121096e-306 1.69119330e-306 1.42413555e-306]


[1.78019082e-306 1.37959740e-306 6.23057349e-307 1.02360935e-306]
[1.69120416e-306 1.78022342e-306 6.23058028e-307 1.06811422e-306]
[9.45699680e-308 1.11261027e-306 1.37961913e-306 9.34604358e-307]]

In [19]:
1 numpy_empty=np.empty((4,4),dtype=int)
2 print(numpy_empty)

[[-1271310320 1071806152 -137438953 1073341267]


[-927712936 1074118262 1374389535 1074339512]
[ 01075314688 01077673984]
[ 01078099968 01083900928]]
Created by :- Sonu Kumar

In [20]:

1 numpy_empty=np.empty((4,4),dtype=complex)
2 print(numpy_empty)

[[1.23160026e-311+1.05730048e-321j0.00000000e+000+0.00000000e+000j
1.42413554e-306+5.02034658e+175j1.21004824e-071+4.23257854e+175j]
[3.41996727e-032+4.90863814e-062j9.83255598e-072+4.25941885e-096j
1.12855837e+277+8.93168725e+271j7.33723594e+223+1.70098498e+256j]
[5.49109388e-143+1.06396443e+224j3.96041428e+246+1.16318408e-028j
1.89935647e-052+9.85513351e+165j1.08805205e-071+4.18109207e-062j]
[2.24151504e+174+3.36163259e-067j5.41760579e-067+3.18070066e-028j
3.93896263e-062+5.74015544e+180j 1.94919988e-153+1.02847381e-307j]]

In [21]:

1 numpy_empty=np.empty((4,4),dtype=bool)
2 print(numpy_empty)
[[ True False True True] [
True True True True] [
True True True True] [
True True True True]]

linspace()

np.linspace(start,stop, num,endpoint, retstep, dtype,axis)

It creates an array with evenly spaced values within specified interval.

In [22]:
1 numpy_linspace=np.linspace(1,37, 37)
2 print(numpy_linspace)

[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.


19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.
37.]

In [23]:

1 numpy_linspace=np.linspace(1,37, 37, dtype=int)


2 print(numpy_linspace)

[123456789101112131415161718192021222324
25 26 27 28 29 30 31 32 33 34 35 36 37]

In [24]:

1 numpy_linspace=np.linspace(1,37, 37, dtype=bool)


2 print(numpy_linspace)

[ True True True True True True True True True True True True
True True True True True True True True True True True True
True True True True True True True True True True True True
True]
Created by :- Sonu Kumar

In [25]:

1 numpy_linspace=np.linspace(1,37, 37, dtype=complex)


2 print(numpy_linspace)

[1.+0.j2.+0.j3.+0.j4.+0.j5.+0.j6.+0.j7.+0.j8.+0.j9.+0.j
10.+0.j 11.+0.j 12.+0.j 13.+0.j 14.+0.j 15.+0.j 16.+0.j 17.+0.j 18.+0.j
19.+0.j 20.+0.j 21.+0.j 22.+0.j 23.+0.j 24.+0.j 25.+0.j 26.+0.j 27.+0.j
28.+0.j 29.+0.j 30.+0.j 31.+0.j 32.+0.j 33.+0.j 34.+0.j 35.+0.j 36.+0.j
37.+0.j]

reshape()
np.reshape(line_number, column_number, order = 'C')

In [26]:
1 numpy_arange= np.arange(1, 37).reshape(6,6)
2 print(numpy_arange)

[[123456]
[7 8 91011 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]
[25 26 27 28 29 30]
[31 32 33 34 35 36]]

In [50]:

1 numpy_exercises= np.arange(16).reshape(4,4)
2 print(numpy_exercises)
3 print(numpy_exercises.size)

[[0 1 2 3]
[4567]
[8 91011]
[12 13 14 15]]
16

In [28]:

1 """
2 Ifthearraysizeisverylargethenonlycornersofthearrayareprinted.
3 Thenthecentralpartofthearrayisskipped.
4 """
5 numpy_exercises= np.arange(10000).reshape(200,50)
6 print(numpy_exercises)

[[ 0 1 2 ... 47 48 49]
[ 50 51 52 ... 97 98 99]
[ 100 101 102 ... 147 148 149]
...
[9850 9851 9852 ... 9897 9898 9899]
[9900 9901 9902 ... 9947 9948 9949]
[9950 9951 9952 ... 9997 9998 9999]]

set_printoption()
Created by :- Sonu Kumar
np.set_printoption(threshold = sys.maxsize)

In [29]:
1 """
2 Toenablenumpytoprinttheentirearray, use'set_printoptions()'method.
3 """
4 importsys
5 numpy_exercises= np.arange(10000).reshape(200,50)
6 np.set_printoptions(threshold = sys.maxsize)
7 print(numpy_exercises)

[[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41
42 43 44 45 46 47 48 49]
[ 50 51 52 53 54 55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72 73 74 75 76 77
78 79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99]
[100 101 102 103 104 105 106 107 108 109 110 111 112 113
114 115 116 117 118 119 120 121 122 123 124 125 126 127
128 129 130 131 132 133 134 135 136 137 138 139 140 141
142 143 144 145 146 147 148 149]
[150 151 152 153 154 155 156 157 158 159 160 161 162 163
164 165 166 167 168 169 170 171 172 173 174 175 176 177
178 179 180 181 182 183 184 185 186 187 188 189 190 191
192 193 194 195 196 197 198 199]
[200 201 202 203 204 205 206 207 208 209 210 211 212 213
214 215 216 217 218 219 220 221 222 223 224 225 226 227
228 229 230 231 232 233 234 235 236 237 238 239 240 241

indexing

Indexing in Python starts with 0.

In [30]:

1 #Using1Darray
2 special_nums= np.array([0.577,1.618, 2.718, 3.14, 6,37, 1729])
3 print(special_nums[0])
4 print(special_nums[-1]) # This shows negative indexing and negative indexing starts with -1.
5 print(special_nums[-3])
6 print(special_nums[2])
7 print(special_nums[5])

0.577
1729.0
6.0
2.718
37.0
Created by :- Sonu Kumar
In [31]:

1 #Using2Darray
2 special_nums=np.array([0,1, 1,2,3,5, 8,13,21, 34,55,89]).reshape(3,4)
3 print(special_nums)
4 print(len(special_nums))
5 print(special_nums[1,1]) #Itmeansfirst line,first column,namelytheoutputis5.
6 print(special_nums[2,3]) #Itmeanssecondline,thirdcolumn,namelytheoutputis 89.

[[0 1 1 2]
[358 13]
[21 34 55 89]]
3
5
8
9

Addition

In [32]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Addedarray')
8 addition=numpy_arange+numpy_array #Addition
9 print(addition)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Added array
[[20.577 29.118]
[37.718 45.64 ]]

Substraction
Created by :- Sonu Kumar

In [33]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Substractedarray')
8 substraction= numpy_arange-numpy_array #Substraction
9 print(substraction)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Substractedarray
[[19.423 25.882]
[32.282 39.36 ]]

Multiplication

In [34]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Multiplicated array')
8 multiplication=numpy_arange*numpy_array #Multiplication
9 print(multiplication)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Multiplicatedarray
[[11.54 44.495]
[ 95.13 133.45 ]]

Division
Created by :- Sonu Kumar
In [35]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Dividedarray')
8 division=numpy_arange/numpy_array # Substraction
9 print(division)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Divided array
[[34.66204506 16.99629172]
[12.87711553 13.53503185]]

Floor division

In [36]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Divisorarray')
8 divisor=numpy_arange//numpy_array #Floordivision
9 print(divisor)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Divisorarray
[[34. 16.]
[12. 13.]]

Modulus
Created by :- Sonu Kumar

In [37]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Modulusarray')
8 modulus=numpy_arange%numpy_array #Modulus
9 print(modulus)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]
Modulusarray
[[0.382 1.612]
[2.384 1.68 ]]

Exponentiation

In [38]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Exponentiated array')
8 exponentiation=numpy_arange**numpy_array #Exponentiation
9 print(exponentiation)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Exponentiatedarray
[[5.63241060e+002.13226068e+02]
[1.57317467e+04 1.29760121e+05]]

@ operator
new_matrix=matrix_1*matrix_2
Returns the product of the two matrices.
Created by :- Sonu Kumar

In [39]:

1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)


2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Productof@operator')
8 array=numpy_arange@numpy_array #@operator
9 print(array)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Productof@operator
[[ 86.285 118.71 ]
[135.71 190.08 ]]

dot()

new_matrix = matrix_1.dot(matrix_2)

It returns the product of the two matrices. It is as same as the @ operator.

In [40]:
1 numpy_arange= np.arange(20,50, 7.5).reshape(2,2)
2 numpy_array= np.array([0.577,1.618, 2.718, 3.14]).reshape(2,2)
3 print(numpy_arange)
4 print()
5 print(numpy_array)
6 print()
7 print('Productofthefunctiondot()')
8 array=numpy_arange.dot(numpy_array) #dot()function
9 print(array)

[[20. 27.5]
[35. 42.5]]

[[0.577 1.618]
[2.718 3.14 ]]

Productofthefunctiondot()
[[ 86.285 118.71 ]
[135.71 190.08 ]]

Relationaloperations
array_name,operator,value

num p y_ar ray< 100


Created by :- Sonu Kumar

In [49]:

1 numpy_array=np.arange(10,50, 5)
2 print(numpy_array< 30)
3 print(numpy_array> 30)
4 print(numpy_array ==30)
5 print(numpy_array!= 30)
6 print(numpy_array >=30)
7 print(numpy_array <=30)

[ True True True True False False False False]


[False False False False False True True True]
[False False False False True False False False]
[ True True True True False True True True]
[False False False False True True True True]
[ True True True True True False False False]

Operations with different types of arrays

It returns a UFuncTypeError.

In [56]:
1 numpy_array_one= np.ones((2, 2), dtype=int)
2 numpy_array_two=np.arange(2, 20.0)
3 numpy_array_one +=numpy_array_two
4 print(numpy_array_one)

------------------------------------------- -------- -------- -------- ------- -


UFuncTypeError Traceback(mostrecentcalllast)
~\AppData\Local\Temp/ipykernel_11868/3374378000.py in <module>
1numpy_array_one=np.ones((2, 2),dtype=int)
2 numpy_array_two = np.arange(2, 20.0)
---->3numpy_array_one+=numpy_array_two
4 print(numpy_array_one)

UFuncTypeError:Cannotcastufunc'add'outputfromdtype('float64')todtype('int32')withcastingrule
'same_kind'

Unary operations

arr ay_nam e.m in()


array_name.max()
array_name.sum()
etc.
Created by :- Sonu Kumar

In [92]:

1 numpy_array =np.arange(1,25).reshape(4, 6)
2 print(numpy_array)
3 print(f'Theminimumelementofthecertainarrayis{numpy_array.min()}.')
4 print(f'Themaximumelementofthecertainarrayis{numpy_array.max()}.')
5 print(f'Thesumoftheelementsofthearrayis{numpy_array.sum()}.')
6 print(f'Themeanoftheelementsofthearrayis{numpy_array.mean()}.')
7 print(f'Thestandarddeviationoftheelementsofthearrayis{numpy_array.std()}.')
8 print(f'Thevarianceoftheelementsofthearrayis{numpy_array.var()}.')
9 print(f'Thelengthoftheelementsofthearrayis{len(numpy_array)}.')
10 print(f'Theshapeofthearrayis{numpy_array.shape}.')
11 print(f'Thedtypeofthearrayis{numpy_array.dtype}.')
12 print(f'Thetypeofthearrayis{type(numpy_array)}.')
13 print(f'Theminimumnumbers ofevery roware {numpy_array.min(axis =1)}.') #axis=1denotestherow.
14 print(f'Themaximumnumbersofeveryroware{numpy_array.max(axis =1)}.')
15 print(f'Theminimumnumbersofeverycolumnare{numpy_array.min(axis=0)}.') #axis=0denotesthecolumn
16 print(f'Themaximumnumbersofeverycolumnare{numpy_array.max(axis=0)}.')
17 print(f'Thesumofthenumbersineachcolumnare{numpy_array.sum(axis=0)}.')
18 print(f'Thesumofthenumbersineachroware{numpy_array.sum(axis=1)}.')
19 print(f'Themeanofthenumbersineachcolumnis{numpy_array.mean(axis=0)}.')
20 print(f'Themeanofthenumbersineachrowis{numpy_array.mean(axis=1)}.')

[[123456]
[7 8 91011 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]
Theminimumelementofthecertainarrayis1.
Themaximumelementofthecertainarrayis24.
The sum of the elements of the array is 300.
The mean of the elements of the array is 12.5.
Thestandarddeviationoftheelementsofthearrayis6.922186552431729.
The variance of the elements of the array is 47.916666666666664.
Thelengthoftheelementsofthearrayis4.
The shape of the array is (4, 6).
The dtype of the array is int32.
The type of the array is <class 'numpy.ndarray'>.
The minimum numbers of every row are [ 1 7 13 19].
The maximum numbers of every row are [ 6 12 18 24].
The minimum numbers of every column are [1 2 3 4 5 6].
The maximum numbers of every column are [19 20 21 22 23 24].
Thesumofthenumbersineachcolumnare[404448525660].
The sum of the numbers in each row are [ 21 57 93 129].
Themeanofthenumbersineachcolumnis[10.11.12.13.14.15.].
The mean of the numbers in each row is [ 3.5 9.5 15.5 21.5].
Created by :- Sonu Kumar
In [93]:

1 print(f'Thecumulativesumofthenumbersineachcolumnis\n{numpy_array.cumsum(axis=0)}.')
2 print(f'Thecumulativesumofthenumbersineachrowis\n{numpy_array.cumsum(axis=1)}.')
3 print(f'Thecumulativesumofthenumbersinthearrayis\n{numpy_array.cumsum()}.')
4 print('etc...')

Thecumulativesumofthenumbersineachcolumnis
[[123456]
[ 8 10 12 14 16 18]
[21 24 27 30 33 36]
[40 44 48 52 56 60]].
Thecumulativesumofthenumbersineachrowis
[[1 3 6101521]
[ 7 15 24 34 45 57]
[13 27 42 58 75 93]
[ 19 39 60 82 105 129]].
The cumulative sum of the numbers in the array is
[ 1 3 6 10 15 21 28 36 45 55 66 78 91105 120 136 153 171
190 210 231 253 276 300].
etc...

Assignment operators in array

In [111]:

1 importmath
2 numpy_array=np.arange(1,25, 3)
3 print('Themainarrayis',numpy_array)
4 numpy_array_addition= numpy_array+ 6
5 print('Byusingthe+=operator,thearrayis',numpy_array_addition)
6 numpy_array_subtraction= numpy_array -6
7 print('Byusing the-= operator,thearrayis', numpy_array_subtraction)
8 numpy_array_multiplication= numpy_array* 6
9 print('Byusingthe*=operator,thearrayis',numpy_array_multiplication)
10 numpy_array_division= numpy_array/ 6
11 print('Byusing the/=operator,thearrayis',numpy_array_division)
12 numpy_array_floor_division= numpy_array// 6
13 print('Byusing the//=operator,thearrayis',numpy_array_floor_division)
14 numpy_array_modulus= numpy_array% 6
15 print('Byusingthe%=operator,thearrayis',numpy_array_modulus)
16 numpy_array_exponentiation= numpy_array** 6
17 print('Byusingthe**=operator,thearrayis', numpy_array_exponentiation)
18

The main array is [ 1 4 7 10 13 16 19 22]


By using the += operator, the array is [ 7 10 13 16 19 22 25 28]
By using the -= operator, the array is [-5 -2 1 4 7 10 13 16]
By using the *= operator, the array is [ 6 24 42 60 78 96 114 132]
By using the /= operator, the array is [0.16666667 0.66666667 1.16666667 1.66666667 2.16666667 2.66
666667
3.16666667 3.66666667]
By using the //= operator, the array is [0 0 1 1 2 2 3 3]
By using the %= operator, the array is [1 4 1 4 1 4 1 4]
Byusingthe**=operator, thearrayis[ 1 4096 117649 1000000 4826809 16777216 470458
81
113379904]
Created by :- Sonu Kumar

In [125]:

1 numpy_array_one= np.arange(1,10).reshape(3,3)
2 print('Thefirst mainarrayis\n',numpy_array_one)
3 numpy_array_two =np.arange(11,20).reshape(3,3)
4 print('Thesecondmainarrayis\n',numpy_array_two)
5 new_array_addition = numpy_array_one + numpy_array_two
6 print('Byusing the+=operator,thenewarraywillbe\n',new_array_addition)
7 new_array_substraction= numpy_array_one- numpy_array_two
8 print('Byusing the-= operator,thenewarraywillbe\n',new_array_substraction)
9 new_array_multiplication = numpy_array_one * numpy_array_two
10 print('Byusing the*=operator,thenewarraywillbe\n',new_array_multiplication)

Thefirstmainarrayis
[[1 2 3]
[4 5 6]
[7 8 9]]
Thesecondmainarrayis
[[11 12 13]
[14 15 16]
[17 18 19]]
Byusingthe+=operator,thenewarraywillbe
[[12 14 16]
[18 20 22]
[24 26 28]]
Byusingthe-=operator,thenewarraywillbe
[[-10-10 -10]
[-10 -10 -10]
[-10 -10 -10]]
Byusingthe*=operator,thenewarraywillbe
[[11 24 39]
[56 75 96]
[119 144 171]]
Created by :- Sonu Kumar

In [126]:

1 new_array_division = numpy_array_one / numpy_array_two


2 print('Byusing the/=operator,thenewarraywillbe\n',new_array_division)
3 new_array_floor_division= numpy_array_one// numpy_array_two
4 print('Byusing the//=operator,thenewarray willbe\n',new_array_floor_division)
5 new_array_modules= numpy_array_one% numpy_array_two
6 print('Byusing the%= operator,thenewarraywillbe \n',new_array_modules)
7 new_array_exponentiation= numpy_array_one** numpy_array_two
8 print('Byusingthe**=operator,thenewarraywillbe\n',new_array_exponentiation)

Byusingthe/=operator,thenewarraywillbe
[[0.09090909 0.16666667 0.23076923]
[0.28571429 0.33333333 0.375 ]
[0.41176471 0.44444444 0.47368421]]
Byusingthe//=operator,thenewarraywillbe
[[0 0 0]
[0 0 0]
[0 0 0]]
Byusingthe%=operator,thenewarraywillbe
[[1 2 3]
[4 5 6]
[7 8 9]]
Byusingthe**=operator,thenewarraywillbe
[[ 1 4096 1594323]
[ 268435456 452807053 -683606016]
[-2094633337 0 -400556711]]

concatenate()

np.concatenate((array_one, array_two,....), axis=0 or 1)

In [135]:

1 numpy_array_one= np.arange(1,10).reshape(3,3)
2 numpy_array_two =np.arange(11,20).reshape(3,3)
3 new_array_one = np.concatenate((numpy_array_one,numpy_array_two),axis=1)
4 print('Thisisthearrayoneobtainedusingaxis= 1\n',new_array_one)
5 new_array_two= np.concatenate((numpy_array_one,numpy_array_two),axis=0)
6 print('Thisisthearraytwoobtainedusingaxis=0\n',new_array_two)

This is the array one obtained using axis = 1


[[123111213]
[4 5 61415 16]
[789171819]]
This is the array two obtained using axis = 0
[[123] [4 5
6] [7 8 9]
[11 12 13]
[14 15 16]
[17 18 19]]
Created by :- Sonu Kumar

In [140]:

1 x=np.array([[0.577,1.618], [2.718,3.14]])
2 y=np.array([[6,28], [37,1729]])
3 z = np.concatenate((x,y),axis = 1)
4 print('Thisisthenewarrayyieldedbyaddingintotherow\n',z)
5 z = np.concatenate((x,y),axis = 0)
6 print('Thisisthenewarrayyieldedbyaddingintothecolumn\n',z)

This is the new array by adding into the row


[[5.770e-011.618e+006.000e+002.800e+01]
[2.718e+00 3.140e+00 3.700e+01 1.729e+03]]
Thisisthenewarraybyaddingintothecolumn
[[5.770e-01 1.618e+00]
[2.718e+00 3.140e+00]
[6.000e+00 2.800e+01]
[3.700e+01 1.729e+03]]

Splitting of 1D arrays
np.array_split(array_name, number_of_splits)

In [143]:
1 array_special_nums = np.array([0.577, 1.618, 2, 2.718, 3.14, 6, 28, 37, 1729])
2 print('Beforesplittingthearray\n',array_special_nums)
3 new_array = np.array_split(array_special_nums,3)
4 print('Aftersplittingthearray\n',new_array)

Before splitting the array


[5.770e-011.618e+002.000e+002.718e+003.140e+006.000e+002.800e+01
3.700e+01 1.729e+03]
After splitting the array
[array([0.577,1.618, 2. ]),array([2.718,3.14, 6. ]),array([28., 37., 1729.])]

In [144]:

1 array_special_nums = np.array([0.577, 1.618, 2, 2.718, 3.14, 6, 28, 37, 1729])


2 print('Beforesplittingthearray\n',array_special_nums)
3 new_array = np.array_split(array_special_nums,6)
4 print('Aftersplittingthearray\n',new_array)
Before splitting the array
[5.770e-011.618e+002.000e+002.718e+003.140e+006.000e+002.800e+01
3.700e+01 1.729e+03]
After splitting the array
[array([0.577, 1.618]), array([2. , 2.718]), array([3.14, 6. ]), array([28.]), array([37.]), array([1729.])]

Splitting of 2D arrays

np.array_split(array_name, number_of_splits, axis=0 or 1)


Created by :- Sonu Kumar

In [146]:

1 array_special_nums=np.array([[0.577,1.618], [2,2.718], [3.14,6],[13, 28],[37, 1729]])


2 print('Beforesplittingthearray\n',array_special_nums)
3 new_array = np.array_split(array_special_nums,2)
4 print('Aftersplittingthearray\n',new_array)

Beforesplittingthearray
[[5.770e-011.618e+00]
[2.000e+002.718e+00]
[3.140e+006.000e+00]
[1.300e+012.800e+01]
[3.700e+01 1.729e+03]]
Aftersplittingthearray
[array([[0.577, 1.618],
[2. , 2.718],
[3.14 , 6. ]]), array([[ 13., 28.],
[ 37., 1729.]])]

In [147]:
1 array_special_nums = np.array([[0.577, 1.618], [2, 2.718], [3.14, 6], [13, 28], [37, 1729]])
2 print('Beforesplittingthearray\n',array_special_nums)
3 new_array= np.array_split(array_special_nums,2, axis=0)
4 print('Aftersplittingthearray\n',new_array)

Beforesplittingthearray
[[5.770e-011.618e+00]
[2.000e+002.718e+00]
[3.140e+006.000e+00]
[1.300e+012.800e+01]
[3.700e+01 1.729e+03]]
Aftersplittingthearray
[array([[0.577, 1.618],
[2. , 2.718],
[3.14,6. ]]),array([[ 13., 28.],
[ 37., 1729.]])]
Created by :- Sonu Kumar

In [148]:

1 array_special_nums=np.array([[0.577,1.618], [2,2.718], [3.14,6],[13, 28],[37, 1729]])


2 print('Beforesplittingthearray\n',array_special_nums)
3 new_array=np.array_split(array_special_nums, 2, axis=1)
4 print('Aftersplittingthearray\n',new_array)
Beforesplittingthearray
[[5.770e-011.618e+00]
[2.000e+002.718e+00]
[3.140e+006.000e+00]
[1.300e+012.800e+01]
[3.700e+01 1.729e+03]]
Aftersplittingthearray
[array([[ 0.577],
[2. ],
[ 3.14 ],
[13. ],
[37. ]]),array([[1.618e+00],
[2.718e+00],
[6.000e+00],
[2.800e+01],
[1.729e+03]])]

Indexing to get subarrays

In [2]:

1 importnumpyasnp
2 array_special_nums = np.array([0.577, 1.618, 2, 2.718, 3.14, 6, 28, 37, 1729])
3 splitted_array = np.array_split(array_special_nums, 5)
4 print('Beforeindexing\n',splitted_array)
5 print('Afterindexing\n',splitted_array[0:2])
6 print('Aftersplitting\n',splitted_array[2:5])
7 print('Aftersplitting\n',splitted_array[1])
8 print('Aftersplitting\n',splitted_array[2])

Before indexing
[array([0.577,1.618]),array([2. , 2.718]), array([3.14,6.]), array([28.,37.]), array([1729.])]
After indexing
[array([0.577,1.618]),array([2. ,2.718])]
After splitting
[array([3.14, 6. ]), array([28., 37.]), array([1729.])]
Aftersplitting
[2. 2.718]
Aftersplitting
[3.14 6. ]

Copy of array

With assignment: new_array = old_array


With shallow copy: new_array = old_array.view()
With deep copy: new_array = old_array.copy()
Created by :- Sonu Kumar
In [17]:

1 # With assignment
2 array_old=np.array([0, 1,1,2,3,5,8,13,21,34])
3 new_array= array_old
4 print('Theoldarrayis',array_old,'andtheidoftheoldarrayis', id(array_old))
5 print('Thenewarray is',new_array,'andtheidofthenewarray is',id(new_array),'whichissameasthatoftheoldar
6 print(id(array_old))
7 foriinarray_old:
8 print(i,end='')
9 print()
10 print(id(new_array))
11 foriinnew_array:
12 print(i,end='')

The old array is [ 0 1 1 2 3 5 8 13 21 34] and the id of the old array is 2017306300016
Thenewarrayis[0112358132134]andtheidofthenewarrayis2017306300016whichissam
easthatofthe oldarray.
2017306300016
0112358132134
2017306300016
0112358132134

In [20]:

1 #Withshallowcopy
2 array_old=np.array([0, 1,1,2,3,5,8,13,21,34])
3 new_array= array_old.view()
4 print('Theoldarrayis',array_old,'andtheidoftheoldarrayis', id(array_old))
5 print('Thenewarrayis',new_array, 'andtheidofthenewarrayis',id(new_array),'whichisdifferent fromthatofthe

The old array is [ 0 1 1 2 3 5 8 13 21 34] and the id of the old array is 2017306299056
Thenewarrayis[0112358132134]andtheidofthenewarrayis2017306299248whichisdiffe
rent from that of the old array.

In [21]:

1#With deepcopy
2 array_old=np.array([0, 1,1,2,3,5,8,13,21,34])
3 new_array= array_old.copy()
4 print('Theoldarrayis',array_old,'andtheidoftheoldarrayis', id(array_old))
5 print('Thenewarrayis',new_array, 'andtheidofthenewarrayis',id(new_array),'whichisdifferent fromthatofthe

The old array is [ 0 1 1 2 3 5 8 13 21 34] and the id of the old array is 2017306297904
Thenewarrayis[0112358132134]andtheidofthenewarrayis2017306296944whichisdiffe
rent from that of the old array.

Searching with where() method

np.where(array_name==element to search)
Created by :- Sonu Kumar

In [24]:

1 fibonacci_nums= np.array([0,1,1, 2, 3, 5, 8, 13, 21, 34])


2 new_array_one= np.where(fibonacci_nums==1)
3 new_array_two= np.where(fibonacci_nums==8)
4 print(new_array_one)
5 print(new_array_two)

(array([1, 2], dtype=int64),)


(array([6], dtype=int64),)

In [25]:

1 fibonacci_nums= np.array([0,1,1, 2, 3, 5, 8, 13, 21, 34])


new_array_one= np.where(fibonacci_nums %2==1) 3
2
new_array_two= np.where(fibonacci_nums%3==0) 4
print(new_array_one) 5 print(new_array_two)

(array([1, 2, 4, 5, 7, 8], dtype=int64),)


(array([0, 4, 8], dtype=int64),)

In [26]:

1 fibonacci_nums= np.array([0,1,1, 2, 3, 5, 8, 13, 21, 34])


new_array_one= np.where(fibonacci_nums //2==1)
2
3 new_array_two= np.where(fibonacci_nums//3==0)
4 print(new_array_one)
5 print(new_array_two)

(array([3, 4], dtype=int64),)


(array([0, 1, 2, 3], dtype=int64),)

Searching with searchsorted() method

np.searchsorted(name_array, value)

In [28]:
1 fibonacci_nums= np.array([0,1,1, 2, 3, 5, 8, 13, 21, 34])
2 new_array = np.searchsorted(fibonacci_nums,2)
3 print(f'The element2infibonaccinumbersisinindex{new_array}.')

The element 2 in fibonacci numbers is in index 3.

Sorting

np.sort(name_array)
Created by :- Sonu Kumar

In [29]:

1 mix_fibonacci_nums=np.array([21,34, 0, 2, 5,3, 8, 1, 1, 13])


2 print('Beforesorting\n', mix_fibonacci_nums)
3 sorted_fibonacci_nums=np.sort(mix_fibonacci_nums)
4 print('Aftersorting\n', sorted_fibonacci_nums)
5

Before sorting
[21340253811 13]
After sorting
[0112358 132134]

In [44]:

1 fruit_array=np.array(['Banana','Orange', 'Erdberry','Apple','Pineapple','Kiwi'])
2 print('Beforesorting\n', fruit_array)
3 fruit_array=np.sort(fruit_array)
4 print('Aftersorting\n', fruit_array)

Before sorting
['Banana' 'Orange' 'Erdberry' 'Apple' 'Pineapple' 'Kiwi']
After sorting
['Apple' 'Banana' 'Erdberry' 'Kiwi' 'Orange' 'Pineapple']

In [47]:

1 mix_fibonacci_nums_2D_array= np.array([[21,34,0],[2,5,3],[8,1,1]])
2 print('Beforesorting\n', mix_fibonacci_nums_2D_array)
3 mix_fibonacci_nums_2D_array=np.sort(mix_fibonacci_nums_2D_array)
4 print('Aftersorting\n', mix_fibonacci_nums_2D_array)
5

Beforesorting
[[21 34 0]
[2 5 3]
[8 1 1]]
Aftersorting
[[ 0 21 34]
[2 3 5]
[1 1 8]]

Statistics

np.mean(array)
np.max(array)
np.min(array)
np.sum(array)
np.std(array)
np.var(array)
np .m edian( array)
Created by :- Sonu Kumar

In [52]:

1 fibonacci_nums= np.array([0,1,1, 2, 3, 5, 8, 13, 21, 34])


2 mean=np.mean(fibonacci_nums)
3 print(f'Themeanis{mean}.')
4 maximum= np.max(fibonacci_nums)
5 print(f'Themaximumis{maximum}.')
6 minimum=np.min(fibonacci_nums)
7 print(f'Theminimumis{minimum}.')
8 total=np.sum(fibonacci_nums)
9 print(f'Thesumis{total}.')
10 standard_deviation= np.std(fibonacci_nums)
11 print(f'Thestandarddeviationis{standard_deviation}.')
12 variance=np.var(fibonacci_nums)
13 print(f'Thevarianceis{variance}.')
14 median=np.median(fibonacci_nums)
15 print(f'Themedianis{median}.')
16 print(f'Thesizeofthearrayis{fibonacci_nums.size}.')
17 print(f'Thelengthofthearrayis{len(fibonacci_nums)}.')

The mean is 8.8.


Themaximumis34.
Theminimumis0.
The sum is 88.
Thestandarddeviationis10.467091286503619.
The variance is 109.55999999999999.
The median is 4.0.
Thesizeofthearrayis10.
The length of the array is 10.

Mathematical functions

In [59]:

1 print(np.pi)
2 print(np.e)
3 print(np.nan)
4 print(np.inf)
5 print(-np.inf)

3.141592653589793
2.718281828459045
nan
inf
-inf

In [65]:

1 a=np.array([0, np.pi/3,np.e/2,np.pi,np.e])
2 print(np.sin(a))
3 print(np.cos(a)
4 )
print(np.tan(a)
)
[0.00000000e+008.66025404e-019.77684488e-011.22464680e-16
4.10781291e-01]
[1. 0.5 0.21007866 -1. -0.91173391]
[0.00000000e+00 1.73205081e+00 4.65389724e+00-1.22464680e-16
-4.50549534e-01]
Created by :- Sonu Kumar

In [78]:

1 importmatplotlib.pyplotasplt
2
3 a=np.linspace(0,np.e*np.pi,num=200)
4 b= np.sin(a)
5 c=np.cos(a)
6
7 plt.plot(a,b, color='red',label='Sin Plot')
8 plt.scatter(a,c,color='green',label='CosPlot')
plt.xlabel('a')
9 plt.ylabel('bandc')
10
plt.legend()
11
plt.grid()
12
13
14
15 plt.show()

In [81]:

1 nlis=[[1,2, 3],[11,12, 13], [14,15, 16]]


2 numpy_array= np.array(nlis)
3 print(numpy_array)
4 print(numpy_array.ndim)
5 print(numpy_array.shape)
6 print(numpy_array.size)
[[123]
[11 12 13]
[14 15 16]]
2
(3, 3)
9
Created by :- Sonu Kumar
In [93]:

1 #Accessing
2 print(numpy_array[0,0])
3 print(numpy_array[0,1])
4 print(numpy_array[0,2])
5 print(numpy_array[1,0])
6 print(numpy_array[1,1])
7 print(numpy_array[1,2])
8 print(numpy_array[2,0])
9 print(numpy_array[2,1])
10 print(numpy_array[2,2])
11 print(numpy_array[0][0:3])
12 print(numpy_array[1][1:3])
13 print(numpy_array[2][0:2])

1
2
3
11
12
13
14
15
16
[1 2 3]
[12 13]
[14 15]

Thanks A Bunch

Follow for more @sonu kumar

You might also like