Numpy ndarrays.pdf

SudhanshiBakre1 57 views 11 slides Sep 16, 2023
Slide 1
Slide 1 of 11
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11

About This Presentation

https://techvidvan.com/tutorials/numpy-ndarrays/


Slide Content

Numpyndarrays
OneofthefundamentalcomponentsofNumPyisthendarray(shortfor
“n-dimensionalarray”).Thendarrayisaversatiledatastructurethatenables
youtoworkwithhomogeneous,multi-dimensionaldata.Inthisguide,we’ll
divedeepintounderstandingndarray,itsstructure,attributes,and
operations.
Introductiontondarrays
Anndarrayisamulti-dimensional,homogeneousarrayofelements,allofthe
samedatatype.Itprovidesaconvenientwaytostoreandmanipulatelarge
datasets,suchasimages,audio,andscientificdata.ndarraysarethelynchpin
ofmanyscientificanddataanalysislibrariesinPython.
Creatingndarrays
FollowTechVidvanonGoogle&Stayupdatedwithlatest
technologytrends
Usingnumpy.array()
Thenumpy.array()functionallowsyoutocreateanndarrayfromanexisting
listoriterable.
importnumpyasnp
data_list=[1,2,3,4,5]
arr=np.array(data_list)

Usingnumpy.zeros()andnumpy.ones()
Youcancreatearraysfilledwithzerosoronesusingthesefunctions.
zeros_arr=np.zeros((3,4))#Createsa3x4arrayofzeros
ones_arr=np.ones((2,2)) #Createsa2x2arrayofones
Usingnumpy.arange()andnumpy.linspace()
numpy.arange()generatesanarraywithevenlyspacedvalueswithina
specifiedrange,whilenumpy.linspace()generatesanarraywithaspecified
numberofevenlyspacedvaluesbetweenastartandend.
range_arr=np.arange(0,10,2) #Arrayfrom0to10with
step2
linspace_arr=np.linspace(0, 1,5) #Arrayof5valuesfrom
0to1
ParametersofthendarrayClass
a.shape
Theshapeparameterisatupleofintegersthatdefinesthedimensionsofthe
createdarray.Itspecifiesthesizeofthearrayalongeachaxis,makingit
possibletocreatearraysofdifferentshapes,fromone-dimensionalto
multi-dimensionalarrays.

b.dtype(datatype)
Thedtypeparameterspecifiesthedatatypeoftheelementswithinthearray.
ItcanbeanyobjectthatcanbeinterpretedasaNumPydatatype.Thisallows
youtocontroltheprecisionandcharacteristicsofthedatastoredinthearray,
whetherit’sintegers,floating-pointnumbers,orothercustomdatatypes.
c.buffer
Thebufferparameterisanoptionalobjectthatexposesthebufferinterface.It
canbeusedtofillthearraywithdatafromanexistingbuffer.Thisisuseful
whenyouwanttocreateanndarraythatsharesdatawithanotherobject,such
asaPythonbytesobjectoranotherndarray.
d.offset
Theoffsetparameterisanintegerthatspecifiestheoffsetofthearraydata
withinthebuffer(ifthebufferparameterisprovided).Itallowsyoutostart
fillingthearrayfromaparticularpositionwithinthebuffer,whichcanbe
usefulforcreatingviewsorsub-arrays.
e.Strides
Thestridesparameterisanoptionaltupleofintegersthatdefinesthestrides
ofdatainmemory.Stridesdeterminethenumberofbytestomoveinmemory
toaccessthenextelementalongeachaxis.Thisparametercanbeusedto
createarrayswithnon-contiguousdatalayouts,enablingefficientoperations
onsub-arraysorviews.
f.order

Theorderparameterspecifiesthememorylayoutorderofthearray.Itcan
taketwovalues:‘C’forrow-major(C-style)orderand‘F’forcolumn-major
(Fortran-style)order.Thememorylayoutaffectshowtheelementsarestored
inmemory,anditcaninfluencetheefficiencyofaccessingelementsin
differentpatterns.
AttributesofthendarrayClass
a.T(Transpose)
TheTattributereturnsaviewofthetransposedarray.Thisoperationflipsthe
dimensionsofthearray,effectivelyswappingrowsandcolumns.Itis
especiallyusefulforlinearalgebraoperationsandmatrixmanipulations.
b.data(Buffer)
ThedataattributeisaPythonbufferobjectthatpointstothestartofthe
array’sdata.Itprovidesadirectinterfacetotheunderlyingmemoryofthe
array,allowingforseamlessinteractionwithotherlibrariesorPython’s
memorybuffers.
c.dtype(DataType)
Thedtypeattributereturnsadtypeobjectthatdescribesthedatatypeofthe
array’selements.Itprovidesinformationabouttheprecision,size,and
interpretationofthedata,whetherit’sintegers,floating-pointnumbers,or
custom-defineddatatypes.
d.flags(MemoryLayoutInformation)

Theflagsattributereturnsadictionarycontaininginformationaboutthe
memorylayoutofthearray.Itincludesdetailslikewhetherthearrayis
C-contiguous,Fortran-contiguous,orread-only.Thisinformationcanbe
crucialforoptimizingarrayoperations.
e.flat(1-DIterator)
Theflatattributereturnsa1-Diteratoroverthearray.Thisiteratorallowsyou
toefficientlytraverseallelementsinthearray,regardlessoftheirshape.It’s
particularlyusefulwhenyouwanttoapplyanoperationtoeachelementinthe
arraywithouttheneedforexplicitloops.
f.imagandreal(ImaginaryandRealParts)
Theimageandrealattributesreturnseparatendarraysrepresentingthe
imaginaryandrealpartsoftheoriginalarray,respectively.Thisisparticularly
relevantforcomplexnumbers,allowingyoutomanipulatetherealand
imaginarycomponentsindividually.
g.size(NumberofElements)
Thesizeattributereturnsanintegerindicatingthetotalnumberofelementsin
thearray.It’saconvenientwaytoquicklydeterminethearray’soverall
capacity.
h.itemsize(ElementSizeinBytes)

Theitemsizeattributereturnsanintegerrepresentingthesizeofasingle
arrayelementinbytes.Thisisessentialforcalculatingthetotalmemory
consumptionofthearray.
i.nbytes(TotalBytesConsumed)
Thenbytesattributeisanintegerindicatingthetotalnumberofbytes
consumedbyallelementsinthearray.It’sacomprehensivemeasureofthe
memoryusageofthearray.
j.ndim(NumberofDimensions)
Thendimattributereturnsanintegerindicatingthenumberofdimensionsin
thearray.Itdefinesthearray’srankororder.
k.shape(ArrayDimensions)
Theshapeattributereturnsatupleofintegersrepresentingthedimensionsof
thearray.Itdefinesthesizeofthearrayalongeachaxis.
l.strides(ByteSteps)
Thestridesattributereturnsatupleofintegersindicatingthenumberofbytes
tostepineachdimensionwhentraversingthearray.Thisinformationis
crucialforunderstandinghowthearray’sdataislaidoutinmemory.
m.ctypes(Interactionwithctypes)

Thectypesattributeprovidesanobjectthatsimplifiestheinteractionofthe
arraywiththectypesmodule,whichisusefulforinteroperabilitywith
low-levellanguageslikeC.
n.base(BaseArray)
Thebaseattributereturnsthebasearrayifthememoryisderivedfromsome
otherobject.Thisisparticularlyrelevantwhenworkingwithviewsorarrays
thatsharememorywithotherarrays.
IndexingandSlicing
Youcanaccesselementswithinanndarrayusingindexingandslicing.
Advertisement
arr=np.array([[1,2,3],[4,5,6]])
print(arr[0,1]) #Output:2(elementatrow0,column1)
print(arr[:,1:3]) #Output:[[2,3],[5,6]](slicingcolumns
1and2)
ArrayOperations
Element-wiseOperations
ndarrayssupportelement-wiseoperationslikeaddition,subtraction,
multiplication,anddivision.
arr1=np.array([1,2,3])
arr2=np.array([4,5,6])
result=arr1+arr2#Element-wiseaddition
print(result)

Output:
[579]
Broadcasting
Broadcastingallowsarrayswithdifferentshapestobecombinedin
operations.
arr=np.array([[1,2,3],[4,5,6]])
scalar=2
result=arr+scalar#Broadcastingscalartoallelements
print(result)
Output:
[[345]
[678]]
ReshapingandTransposing
Youcanreshapeandtransposendarraystochangetheirdimensionsand
orientations.
arr=np.array([[1,2,3],[4,5,6]])
reshaped_arr=arr.reshape((3, 2))#Reshapingto3x2
transposed_arr =arr.T #Transposingthearray
print("Original Array:")
print(arr)
print("\nReshaped Array(3x2):")
print(reshaped_arr)

print("\nTransposed Array:")
print(transposed_arr)
Output:
OriginalArray:
[[123]
[456]]
ReshapedArray(3×2):
[[12]
[34]
[56]]
TransposedArray:
[[14]
[25]
[36]]
AggregationandStatisticalFunctions
NumPyprovidesnumerousfunctionsforcalculatingaggregatesandstatistics.
arr=np.array([1,2,3,4,5])
mean=np.mean(arr)
median=np.median(arr)
std_dev=np.std(arr)
print("Array:", arr)
print("Mean:", mean)
print("Median:", median)

print("Standard Deviation:",std_dev)
Output:
Array:[12345]
Mean:3.0
Median:3.0
StandardDeviation:1.4142135623730951
BooleanIndexingandFancyIndexing
Booleanindexingallowsyoutoselectelements
basedonconditions.
arr=np.array([10,20,30,40,50])
mask=arr>30
result=arr[mask]
Output:[40,50]
Fancyindexinginvolvesselectingelementsusing
integerarrays.
arr=np.array([1,2,3,4,5])
indices=np.array([1,3])
result=arr[indices]
Output:[2,4]
Conclusion

Inthistutorial,we’veexploredtheworldofndarraysinNumPy.We’ve
venturedintocreatingndarrays,understandingtheirattributes,performing
variousoperations,andeventouchingonadvancedindexingtechniques.The
ndarray’sversatilityandefficiencymakeitanessentialtoolfornumerical
computationsanddataanalysisinPython.Withtheknowledgegainedhere,
you’rewell-equippedtostartharnessingthepowerofNumPyndarraysfor
yourownprojects.Happycoding!
Tags