NumPy For Data Science
NumPy For Data Science
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
In [1]:
1 importnumpyasnp
You can find more information about NumPy when executing the following commands.
In [2]:
1
# help(np)
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: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)
arange()
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))
In [13]:
1 numpy_zeros=np.zeros((3,4),dtype=bool)
2 print(numpy_zeros)
3 print(type(numpy_zeros))
ones()
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))
In [17]:
1 numpy_ones=np.ones((3,4),dtype=bool)
2 print(numpy_ones)
3 print(type(numpy_ones))
empty()
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)
In [19]:
1 numpy_empty=np.empty((4,4),dtype=int)
2 print(numpy_empty)
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()
In [22]:
1 numpy_linspace=np.linspace(1,37, 37)
2 print(numpy_linspace)
In [23]:
[123456789101112131415161718192021222324
25 26 27 28 29 30 31 32 33 34 35 36 37]
In [24]:
[ 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.+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
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]:
[[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]:
[[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]:
[[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]:
[[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]:
[[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]:
[[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]:
[[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]:
[[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)
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
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)
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:Cannotcastufunc'add'outputfromdtype('float64')todtype('int32')withcastingrule
'same_kind'
Unary operations
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...
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
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]:
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()
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)
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)
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)
In [144]:
Splitting of 2D arrays
In [146]:
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]:
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
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.
np.where(array_name==element to search)
Created by :- Sonu Kumar
In [24]:
In [25]:
In [26]:
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}.')
Sorting
np.sort(name_array)
Created by :- Sonu Kumar
In [29]:
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]:
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 #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