Table Of ContentPython For Data Science Cheat Sheet Inspecting Your Array Subsetting, Slicing, Indexing Also see Lists
Array dimensions
NumPy Basics >>> a.shape Length of array Subsetting
>>> len(a) Number of arra y d im e nsions >>> a[2] 1 2 3 Select the element at the 2nd index
Learn Python for Data Science Interactively at www.DataCamp.com >>> b.ndim Number of array elements 3
>>> e.size Data type of array element s >>> b[1,2] 1 .5 2 3 Select the element at row 1 column 2
>>> b.dtype Name of data type 6.0 4 5 6 (equivalent to b[1][2])
>>> b.dtype.name
Convert an array to a different type Slicing
>>> b.astype(int)
NumPy >>> a[0:2] 1 2 3 Select items at index 0 and 1
2 Asking For Help array([1, 2])
The NumPy library is the core library for scientific computing in >>> b[0:2,1] 1 .5 2 3 Select items at rows 0 and 1 in column 1
Python. It provides a high-performance multidimensional array >>> np.info(np.ndarray.dtype) array([ 2., 5.]) 4 5 6
object, and tools for working with these arrays. Array Mathematics > > > b[:1] 1 .5 2 3 Select all items at row 0
array([[1.5, 2., 3.]]) 4 5 6 (equivalent to b[0:1, :])
Use the following import convention: Arithmetic Operations >>> c[1,...] Same as [1,:,:]
array([[[ 3., 2., 1.],
>>> import numpy as np >>> g = a - b Subtraction [ 4., 5., 6.]]]) Reversed array
NumPy Arrays array([[-0.5, 0. , 0. ], >>> a[ : :-1] a
array([3, 2, 1])
[-3. , -3. , -3. ]]) Boolean Indexing
1D array 2D array 3D array >>> np.subtract(a,b) Subtraction Select elements from less than 2
>>> b + a Addition >>> a[a<2] 1 2 3 a
axis 1 axis 2 array([[ 2.5, 4. , 6. ], array([1])
1 2 3 axis 1 [ 5. , 7. , 9. ]]) Fancy Indexing
axis 0 14.5 25 36 axis 0 >>>>>> nap ./a dbd ( b , a ) ADdivdisitiioonn > >a>r rba[y[(1[, 4 .0 ,, 12,. ,0 ]6,.[ ,0 ,1 .15,] )2 , 0]] Select elements (1,0),(0,1),(1,2) and (0,0)
array([[ 0.66666667, 1. , 1. ], >>> b[[1, 0, 1, 0]][:,[0,1,2,0]] Select a subset of the matrix’s rows
Creating Arrays > > > n p . [d i0v.2i5d e ( a , ,b ) 0. 4 , 0. 5 ] ] ) Division a r r a y ([[ [1 .45., ,25.. ,, 36.. ,, 14..5 ]],, and columns
>>> a * b Multiplication [[ 14..5 ,, 25.. ,, 36.. ,, 14..5 ]]],)
array([[ 1.5, 4. , 9. ],
>>> a = np.array([1,2,3]) [ 4. , 10. , 18. ]]) Array Manipulation
>>> b = np.array([(1.5,2,3), (4,5,6)], dtype = float) >>> np.multiply(a,b) Multiplication
>>> c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]], >>> np.exp(b) Exponentiation Transposing Array
dtype = float) >>> np.sqrt(b) Square root
Initial Placeholders >>>>>> nnpp..scions((ab)) PElreinmt esninte-ws oisfe a cno asrinraey >>>>>> ii .=T n p . t r a n s p o s e ( b ) PPeerrmmuuttee aarrrraayy ddiimmeennssiioonnss
>>> np.log(a) Element-wise natural logarithm Changing Array Shape
>>>>>> nnpp..zoenreoss(((2(,33,,44)),)d t y p e = n p . i n t 1 6 ) CCrreeaattee aann aarrrraayy ooff zoenreoss > >a>r rea.yd([o[t (7f.), 7 . ] , Dot product >>> b.ravel() Flatten the array
Create an array of evenly Reshape, but don’t change data
>>> d = np.arange(10,25,5) [ 7., 7.]]) >>> g.reshape(3,-2)
sCpreaaceted avna laurerasy (s otefp e vvaelnuely) Comparison Adding/Removing Elements
> >>>>> >>>>> >>>> n efnnp pp. ==..l rei nnamn ppnps ..dtp feoya uym(c le.(e l(r3( (2a,0 ()n2, 2 d)2 , o), 2 m 9 ) ( ) , ( 7 2 ) , 2 ) ) sCCCCprrrreeeeaaaaacetttteeeed aaaavn nac2 olXeaunrm2ers aspitdy a(tn eynwun taim ttraihrbtray rerya ram yon fad s tora immx p vleaslu)es > > >>a >>r r aaa y =( <[ = [[ 2FFb aa ll ss ee ,, F aT lr su ee,, F aT lr su ee]] ,] , d t yp e = b o o l) EElleemmeenntt--wwiissee ccoommppaarriissoonn >>>> >>>>C>>>>o mhnnn.pppbr...ieaidnspneiipslnzeeegenrt (dteA((((r2haar,,,,a6g [y))11s) ,] ) 5 ) RAIDnepestpleueertrtnen id tiate i entmmeesmws i snf a r toraornma a ya na rw nraa iratyrhrar yashyape (2,6)
I/O > >a>r rnapy(.[aTrrruaey,_ Feaqlusael,( Faa,l sbe)] , d t y p e =b o o l ) Array-wise comparison >>> np.concatenate((a,d),axis=0) Concatenate arrays
array([ 1, 2, 3, 10, 15, 20])
Aggregate Functions >>> np.vstack((a,b)) Stack arrays vertically (row-wise)
Saving & Loading On Disk array([[ 1. , 2. , 3. ],
Array-wise sum [ 1.5, 2. , 3. ],
>>> a.sum() [ 4. , 5. , 6. ]])
>>> np.save('my_array', a) >>> a.min() Array-wise minimum value >>> np.r_[e,f] Stack arrays vertically (row-wise)
>>> np.savez('array.npz', a, b) >>> b.max(axis=0) Maximum value of an array row >>> np.hstack((e,f)) Stack arrays horizontally (column-wise)
>>> np.load('my_array.npy') >>> b.cumsum(axis=1) Cumulative sum of the elements array([[ 7., 7., 1., 0.],
Saving & Loading Text Files >>> a.mean() Mean [ 7., 7., 0., 1.]])
>>> b.median() Median >>> np.column_stack((a,d)) Create stacked column-wise arrays
Correlation coefficient
>>>>>> nnpp..lgoeandftrxotm(tx"tm(yfi"lmey._tfixlte".c)sv", delimiter=',') >>>>>> an.pc.osrtrdc(obe)f ( ) Standard deviation a r r a y ( [ [[[ 123,,, 112050]]],,])
Create stacked column-wise arrays
>>> np.savetxt("myarray.txt", a, delimiter=" ") >>> np.c_[a,d]
Copying Arrays Splitting Arrays
Data Types Split the array horizontally at the 3rd
Create a view of the array with the same data >>> np.hsplit(a,3)
>>> h = a.view() index
>>>>>> nnpp..iflnota6t43 2 SStigannedda r6d4 d-obuitb ilnet-epgreerc itsyipoens fl oating point >>>>>> nhp .=c oap.yc(oap)y ( ) CCrreeaattee aa cdoepepy ocof pthye o afr trhaey array >[a>[r>ar ranryap(y.[([v[[s1 p]1l).,i5at,r (r ca2,y.2( [),2 ] )1 ,. a r]r ,a y ( [ 3 ]) ] Split the array vertically at the 2nd index
>>> np.complex Complex numbers represented by 128 floats [ 4. , 5. , 6. ]]]),
>>> np.bool BPyotohleoann o tbyjpeec ts ttyoprieng TRUE and FALSE values Sorting Arrays a r r a y ( [ [ [[ 34..,, 25..,, 36..]],]])]
>>> np.object
Fixed-length string type Sort an array
>>> np.string_ >>> a.sort() DataCamp
Fixed-length unicode type Sort the elements of an array's axis
>>> np.unicode_ >>> c.sort(axis=0) Learn Python for Data Science Interactively