SlidePub
Home
Categories
Login
Register
Home
General
Numpy ndarrays.pdf
Numpy ndarrays.pdf
SudhanshiBakre1
57 views
11 slides
Sep 16, 2023
Slide
1
of 11
Previous
Next
1
2
3
4
5
6
7
8
9
10
11
About This Presentation
https://techvidvan.com/tutorials/numpy-ndarrays/
Size:
87.9 KB
Language:
en
Added:
Sep 16, 2023
Slides:
11 pages
Slide Content
Slide 1
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)
Slide 2
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.
Slide 3
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
Slide 4
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)
Slide 5
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)
Slide 6
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)
Slide 7
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)
Slide 8
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)
Slide 9
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)
Slide 10
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
Slide 11
Inthistutorial,we’veexploredtheworldofndarraysinNumPy.We’ve
venturedintocreatingndarrays,understandingtheirattributes,performing
variousoperations,andeventouchingonadvancedindexingtechniques.The
ndarray’sversatilityandefficiencymakeitanessentialtoolfornumerical
computationsanddataanalysisinPython.Withtheknowledgegainedhere,
you’rewell-equippedtostartharnessingthepowerofNumPyndarraysfor
yourownprojects.Happycoding!
Tags
Categories
General
Download
Download Slideshow
Get the original presentation file
Quick Actions
Embed
Share
Save
Print
Full
Report
Statistics
Views
57
Slides
11
Age
808 days
Related Slideshows
22
Pray For The Peace Of Jerusalem and You Will Prosper
RodolfoMoralesMarcuc
30 views
26
Don_t_Waste_Your_Life_God.....powerpoint
chalobrido8
32 views
31
VILLASUR_FACTORS_TO_CONSIDER_IN_PLATING_SALAD_10-13.pdf
JaiJai148317
30 views
14
Fertility awareness methods for women in the society
Isaiah47
29 views
35
Chapter 5 Arithmetic Functions Computer Organisation and Architecture
RitikSharma297999
26 views
5
syakira bhasa inggris (1) (1).pptx.......
ourcommunity56
28 views
View More in This Category
Embed Slideshow
Dimensions
Width (px)
Height (px)
Start Page
Which slide to start from (1-11)
Options
Auto-play slides
Show controls
Embed Code
Copy Code
Share Slideshow
Share on Social Media
Share on Facebook
Share on Twitter
Share on LinkedIn
Share via Email
Or copy link
Copy
Report Content
Reason for reporting
*
Select a reason...
Inappropriate content
Copyright violation
Spam or misleading
Offensive or hateful
Privacy violation
Other
Slide number
Leave blank if it applies to the entire slideshow
Additional details
*
Help us understand the problem better