Unit II - Advance Python Program: Q&A Extract
print
Arrays are a coll ecti on of the same type of elemen ts/ values that can hav e o ne or more
NumP y arrays a re c all ed
n d array
d im en sion al arrays.
n d array
li st, tu p le or an y array
array()
Dim en sion sin Arrays
A dimension i n arrays i s one level
n p .array(
D array u sin g li st
an d array()
arr = n p .array([
D array u sin g tup le
an d array()
arr = n p .array(
D array u sin g
array()
print
D array u sin g li st and asarray()
print
D array u sin g loop
and n d array()
input
Unit II - Advance Python Program: Q&A Extract
print
input
print
"Array elements : "
Array elements : [1 23 4 5]
empt y_array
print
"Emp ty Array:
empt y_array
Empt y Array:
empt y_array
print
"Emp ty Array:
empt y_array
E m p ty Array:
print
z er os_array
print
z er os_array
print
one s_array
print
one s_array
print
print
Unit II - Advance Python Program: Q&A Extract
print
print
print
print
Rand om Float Array :
print
Output:
print
Output:
D array u sin g li st
an d array()
print
D array u sin g li st and
array()
print
D array u sin g loop and n d array()
input
input
print
input
print
"Array elements:
Array elements:
empt y_array
print
Unit II - Advance Python Program: Q&A Extract
"Emp ty Array:
empt y_array
Empt y Array:
empt y_array
print
"Emp ty Array:
empt y_array
Empt y Array:
print
z er os_array
print
z er os_array
print
one s_array
print
one s_array
print
Rand om n um b ers in ndarray
Rand om Float Array :
print
print
Output:
print
print
D arrays
Unit II - Advance Python Program: Q&A Extract
D array u sin g li st and array()
arr = n p .array([ [[
D array u sin g
array()
input
input
input
print
input
print
"Array elements:
Array elements:
empt y_array
print
"Emp ty Array:
empt y_array
Empt y Array:
empt y_array
print
"Emp ty Array:
empt y_array
Empt y Array:
print
z er os_array
print
Unit II - Advance Python Program: Q&A Extract
z er os_array
print
one s_array
print
one s_array
print
Rand om n um b ers in ndarray
Rand om Float Array :
print
print
Output:
The Sha pe and R esha ping of Num Py Array
S h ap e of an Array
NumP y arrays hav e an att ribute call ed
S h ap e of an Array u sing 1D
array = np.ar ray( [1, 2, 3, 4, 5])
print(arr ay.shape )
S h ap e of an Array u sing 2D
print(arr.shap e)
S h ap e of an Array u sing 3D
array = np.ar ray( [[[1, 2, 3], [4, 5, 6]],
print(arr ay.shape )
1D Array
array_1d = np.a rray ([1, 2 , 3, 4, 5])
print("S hape of the a rray: ",
Unit II - Advance Python Program: Q&A Extract
array_1d.sh ape
print("Number of dim ens ions: ", array
print("Total number of el ements: ", array
2D Array
array_2d = np.a rray ([[1, 2, 3], [4, 5, 6]] )
print("S hape of the a rray: ",
array_
print("Number of dim ens ions: ", array
print("Total number of el ements: ", array
array
print("S hape of the a rray: ", array
print("Number of dim ens ions: ", array
print("Total number of el ements: ", array
Resh ap in g the Nu m PYarray
R eshapingarraysinNum P yisapowerfulfeaturet hatall owsyoutochangethedim ension sofanarra ywithout
a 1D array t o a 2D array:
dim ension alarrayint oamul ti
array_1d = np.a rray ([1, 2 , 3, 4, 5, 6])
array_2d = ar ray_1d. resh ape(2, 3)
print(arr ay_2d)
Output:
a 1D array t o a 3D array:
array_1d = np.a rray ([1, 2 , 3, 4, 5, 6])
array_3d = ar ray_1d. resh ape(2, 1, 3)
print(arr ay_3d)
Unit II - Advance Python Program: Q&A Extract
2d in to 3d Nu m Py array
array_2d = np.a rray ([[1, 2, 3], [4, 5, 6]] )
array_3d = ar ray_2d. resh ape(2, 1, 3)
print(arr ay_3d)
Output:
Resh ap in g a 1D Array t o 2D and 3D
Resh ap in g a 2D Array t o 1D and 3D
Resh ap in g a 3D Array t o 1D and 2D
array_3d = np.a rray ([[[1, 2, 3], [4, 5, 6]],
array_1d = ar ray_3d. resh ape(12)
print("R eshaped to 1D a r ray:" )
print(arr ay_1d)
array_2d = ar ray_3d. resh ape(4, 3)
print("
nR eshaped to 2D array:" )
print(arr ay_2d)
array_1d = np.a rray ([1, 2 , 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
array_2d = ar ray_1d. resh ape(3,
print(arr ay_2d)
Flatten in g a Num Py array
dim ension alarray int oaon e
array = np.ar ray( [[1, 2, 3 ], [4, 5, 6]] )
print(flattened_a rray )
array =
print(raveled_ arr ay)
Unit II - Advance Python Program: Q&A Extract
Flattening NumP y arrays can be very useful whe n deali ng with different dim ension s. Here are ex ampl es
of
1D Array :
array_1d = np.a rray ([1, 2 , 3, 4, 5])
print(flattened_a rray_1d )
2D Array :
array_2d = np.a rray ([[1, 2, 3], [4, 5, 6]] )
print(flattened_a rray_2d )
3D Array :
array_3d =
print(flattened_a rray_3d )
1D Array :
dim ension al arrays.
array_1d = np.a rray ([1, 2 , 3, 4, 5])
print(transposed_a rray_1 d)
Output:
2D Array :
array_2d = np.a rray ([[1, 2, 3], [4, 5, 6]] )
print(transposed_a rray_2 d)
print(transposed_a rray_2 d_T)
Output:
Array :
array_3d = np.a rray ([[[1, 2], [3, 4]], [[5, 6], [7, 8 ]] ])
print(transposed_a rray_3 d)
Expand ing and S queezing a N umP y Array
Unit II - Advance Python Program: Q&A Extract
Expanding and squee zin g a NumP y array ar e co mm on operati ons i n NumP y for adding or remov ing
array_1d = np.a rray ([1, 2 , 3, 4, 5])
print(expanded_ arr ay)
print(expanded_ arr ay.sha pe)
# creati ng an input a rray
print(a.shape )
print(b.shape)
print("Origi nal arr ay:" , ar r)
print("Expanded a rray:" , expanded_ arr)
print("S hape of exp ande d array:" , exp anded_ arr.s hape)
print("Expanded a rray us ing None indexing:" , expanded_ar r_none)
print("S hape of exp ande d array usi ng Non e index ing: ", expanded_ar r_non e.shape)
print("Our Arr ay...",ar r)
print("Array S hap e...",arr .shape)
print("Dimensions of our Array...",a rr.ndim )
print("Datatype of ou r Ar ray object..." ,a rr.dtype)
# Get t he number of ele ments i n an array
print("S ize of arr ay...",ar r.size)
print("R esult ant expande d array....", res)
print("S hape of the exp a nded arr ay...",res.sh ape)
print("Dimensions of our Array...",r es.ndi m)
Output:
Array S hap e...
f uncti on is used to add ne w dimensions t o arrays b y
print('Array x:' )
Unit II - Advance Python Program: Q&A Extract
print(x)
print('
print('Array y with a new axis added at posi ti on 0:')
print(y)
print('
print('The shape o f x and y arrays:')
print(x.shape, y.shap e)
print('
print('Array y afte r insert ing axis at posi ti on 1:')
print(y)
print('
print('x.ndim and y.ndim: ')
print(x.ndim, y.ndi m)
print('
print('x.shape and y.sh ap e:')
print(x.shape, y.shap e)
Array x:
Array y with a n ew axis ad d ed at posi tion 0:
sh ap e of xan d y arrays:
Array y af ter in se rtin g axis at posi tion 1:
dim ension al NumP y array invol ves removi ng dim ension s of size 1.
print("Origi nal arr ay sha pe:" , arr.shap e)
print("S queezed arr ay sh ape:" , squeez ed_a rr.shap e)
print("S queezed arr ay:" , squeezed_ arr )
print("Origi nal arr ay sha pe:" , arr.shap e)
Unit II - Advance Python Program: Q&A Extract
print("S queezed arr ay sh ape:" , squeez ed_a rr.shap e)
print("S queezed arr ay:" , squeezed_ arr )
array_3d = np.a rray ([[[1, 2, 3]], [[4, 5, 6 ]]])
print(arr ay_3d.shape )
print(squeez ed_ar ray)
print(squeez ed_ar ray.sha pe)
d im en sion al Num Py array
print("Origi nal arr ay sha pe:" , arr.shap e)
print("S queezed arr ay sh ape:" , squeez ed_a rr.shap e)
print("S queezed arr ay:" , squeezed_ arr )
array s in N u mPy is straigh tfor ward with the np .so rt() fun ctio n .Let me
sh o w yo u ho w to so rtarray s:
# Sortin g the array
p rint("Orig in al array :", a rr)
Origin al array : [5 2 9 1 5 6 ]
So rted 2 D array al o n g axis 0 (colu mn s):
So rted 2 D array al o n g axis 1 (ro ws):
array :
p lace so rt ed array:
# In d ices th at wou ld so rtth e array
p rint("Array so rted us in g ind ices:",
Ind ices o fth e so rte d array:
Array so rted us in g ind ices:
In d exin g and S licin g of Nu m Py Array
1D array
Unit II - Advance Python Program: Q&A Extract
Ind exingrefe rstoaccessi ngelementsofanarrayusing theirindi ces.NumPyarraysarez ero
print("Element at index 0 :" , arr[0] )
print("Element at index 3 :" , arr[3] )
In d exin g 2D array
print("Element at row 0, colum n 1:" , element_0_1)
print("Element at row 2, colum n 2:" , element_2_2)
Output:
Dim en sion al Arrays
dim ensional arrays is quit e simi lar to 1D and 2D arrays but with more dim ension s to
3D Array E xam p le
print("Element at layer 0, row 1, colum n 2:" , element_0_1_2)
print("Element at layer 1, row 0, colum n 1:" , element_1_0_1)
Output:
S li cin g in 1D Num Py arrays
print(arr[1:5 ])
print(arr[4: ])
print(arr[:4 ])
print(arr[
arr = n p .array([1, 2, 3, 4, 5, 6, 7])
print("S li ce from i ndex 1 to 4: ", s li ce_1)
print("S li ce from st art to i ndex 3:" , sli ce_2)
print("S li ce from i ndex 2 to end:", sl ice_3)
print(sli ce_1) # Output: [2 34 5]
print(sli ce_2) # Output: [0 12 3 4 5]
print(sli ce_3) # Output: [5 67 8 9]
Unit II - Advance Python Program: Q&A Extract
print(sli ce_4) # Output: [0 24 6 8]
print(sli ce_5) # Output: [1 47]
Mod ify Array E lem en ts Usin g S li cin g
sli cing, we can also modi fy array elements u sing:
print(numbers)
# Output:
print(numbers)
print(numbers)
print(numbers)
Num Py Array Negative S li cin g
to per form neg ati ve sli cing in NumP y arrays. During neg ati ve sli cing,
print(numbers[
print(numbers[
print(numbers[
print(reve rsed_numbers )
S li cin g a 2D array u sing Num Py
print(arr[1, 1:4 ])
print(arr[0:2, 2 ])
print(arr[0:2, 1:4] )
array1 = np.ar ray( [[1, 3, 5, 7],
print(arr ay1[:2, :2])
array = np.ar ray( [[1, 2, 3, 4],
element = a rray [1, 2] # Output: 7
E xtract a sub array
subarray = ar ray[0:2, 1:3 ] # Output : [[2, 3], [6, 7] ]
Unit II - Advance Python Program: Q&A Extract
array1 = np.ar ray( [[1, 3, 5, 7],
subarray1 = ar ray1[:2, :2 ]
subarray2 = ar ray1[1:3, 2 :4]
# print t he subarrays
print("First Two Rows a nd C olum ns:
n",s ubarray1)
print("Last t wo Rows and C olum ns:
n",s ubarray2)
array1 [:2,:2]
array1 [1:3,2:4]
Write a P ython P rogram using Numpy array with
Let's s ay we h ave the foll owing 3D numpy array:
S tack in g Num Py Array
S tacking arrays in Num P y refers to combi ning mul ti ple arrays along a new dim ension , cre ati ng higher
dim ension alarrays. Thisisdiffer entfromconcat en ati on,whichcombi nesarr aysalonganexist ingaxiswithout
Stacki ng Arrays Usin g stack()
A sequ ence o f arrays t o be st acked.
In the below ex ampl e, we are sta cking three 1 D arrays along a ne w ax is (axis 0) using the numpy.s
tack()
print("S tacked Arr ay alo ng a new axis ( Axis 0):")
print(stacked_a rr)
# arrays
print("S tacked Arr ay alo ng Axis 1: ")
print(stacked_a rr)
dim ension al Arrays
Unit II - Advance Python Program: Q&A Extract
dim ension a l arrays and st acks t hem accordingly.
print("S tacked 2D Ar ray s along a new axis (Axis 0):")
print(stacked_a rr)
S tacking Arrays Using c olum n_st ack() Fun cti on
The numpy.column_st ac k() functi on in NumP y is used to stack 1D arrays as colum ns int o a 2D array or to
is a tupl e of arrays t o be stacked. The a rrays can be eit he r 1D or 2D, but t hey must have the same
In the ex ampl e below, we are sta cking two two 1D arrays as colum ns int o a 2D array using the NumP y
print("S tacked 1D a rrays as 2D ar ray:" )
print(stacked_a rr_1d)
S tacked 1D ar rays as 2D array:
print("S tacked 2D a rrays colum n
print(stacked_a rr_2d)
is a tupl e of arrays t o be st acked v erti call y. All arr ays m ust have the same numbe r of c olum ns.
arrays
print("Verticall y S tacked Array:" )
print(stacked_a rr)
arrays.
This result s in an array with an increased number of colum ns, combi ning mul ti ple arrays colum n
tupl e of arrays t o be st acked ho riz ontally. All arrays m ust have the same numb er of r ows.
print("Horizontall y S tack ed Arr ay:" )
print(stacked_a rr)
The numpy.ds tack() fun cti on is used to stack arrays along the thi rd dimension , also known as the depth
dim ension . This combines arrays d epth
Itisparticula rlyusefulw henyouwanttocombi ne mul ti ple2Darraysint oasingl e3Darray. Foll owingisthe
Unit II - Advance Python Program: Q&A Extract
is a tupl e of arrays to be stacked alon g the thi rd dim ension . All arrays must have the same shape
print("Depth
wise S tack e d Array:" )
print(stacked_a rr)
Concaten atin g n d arrays
C oncatenati ng ndarr ays refe rs to the process of joi ning multi ple NumP y arrays along a spe cified axis. In
array1 = np.ar ray( [[1, 2], [3, 4]])
array2 = np.ar ray( [[5, 6] ] )
np.conc atenat e(( array1, arr ay2), axis =0)
print(result )
array1 = np.ar ray( [[1, 2], [3, 4]])
array2 = np.ar ray( [[5, 6], [7, 8]])
result = np.conc atenat e(( array1, arr ay2), axis =1)
print(result )
Concaten atin g m u ltiple nd arrays:
array1 = np.ar ray( [1, 2])
array2 = np.ar ray( [3, 4])
array3 = np.ar ray( [5, 6])
# C oncatenati ng mul ti ple ndarrays
result = np.conc atenat e(( array1, arr ay2, ar ray3) )
print(result )
You can use the axis par ameter to control the axis along which the arrays will be joi ned. axis=0 means
along
array so t hat t hey h ave c ompatibl e shapes.
Unit II - Advance Python Program: Q&A Extract
S uppose you have the fol lowing arrays:
array1 = np.ar ray( [1, 2, 3 ])
array2 = np.ar ray( [[1], [2 ], [3]] )
arr ay1 and array2 are (3,) and (3, 1) respecti vely.
print(result )
array = np.ar ray( [1, 2, 3] )
print(result )
# Output: [3 45]
T wo Arrays:
array1 = np.ar ray( [[1, 2, 3], [4, 5, 6]] )
array2 = np.ar ray( [1, 2, 3 ])
print(result )
# Output: [[2 4 6]
on arrays o f diffe ring sha pes easier and more int ui ti ve.
array = np.ar ray( [[1, 2, 3 ], [4, 5, 6]] )
print(result )
# Output: [[10 20 30]
array1 = np.ar ray( [[1, 2, 3], [4, 5, 6]] )
array2 =
print(result )
# Output: [[2 4 6]
array1 = np.ar ray( [[1, 2, 3], [4, 5, 6], [7, 8, 9 ]])
array2 = np.ar ray( [1, 2, 3 ])
print(result )
# Output: [[ 1 4 9]
Unit II - Advance Python Program: Q&A Extract
array1 = np.ar ray( [[1, 2], [3, 4], [5, 6] ])
array2 = np.ar ray( [[10], [ 20]])
print(result )
# Output: [[11 12]
d im en sion al arrays:
array1 = np.ar ray( [[[1, 2 ] , [3, 4]], [ [5, 6], [7, 8] ]])
array2 = np.ar ray( [1, 2])
print(result )
# Output: [[[ 2 4]
These exampl es shoul d give you a bett er sense of how broadcasti ng works with various array shapes and
Creatin g a S eries from a Num Py Array
d ata = np .array(['r', 'a' , 'a' , 'k ', 'i' ])
d ata = np .array(['r', 'a' , 'a' , 'k ', 'i' ])
print(ser)
d ata = np .array(['r','a' ,'g' ,'h ','u ',' e',' n',' g',' g',' c','o' ,'l ',' l',' e',' g',' e'])
print(data.iloc[3:6])
print(df)
print(df['Nam e'])
print(df.loc[1] ) # Bob's r ow
print(fil tered_df )
print(df)
print("Mean Age:" , me an _age)
print(df)
print(df)
print(sorted_df)
Unit II - Advance Python Program: Q&A Extract
print(grouped_df )
print(merged_df )
print(df)
print(pivot)
print(result )
print(result )
print(result )
print(df_filled)
print(df)
print(df_filled)
print(df)
print(df)
print(grouped)
print(grouped)
print(grouped)
print(df)
print(fil tered)
print(df_text)
print(df_csv)
print(df_exc el)
print(df)
print(df)
print(df)
print( df_lo a ded)
print( df)
Unit II - Advance Python Program: Q&A Extract
print (ti tle. text)
print( df.h ea d() )
print(
print( (df
print( z)
print(sca led_ d f.h ea d())
print(" Standa rdi zed Data:" )
print(s tanda rdize d_ df)
print(sca led_ d f.h ea d())
print(" Orig ina l D a ta:")
print( df)
print("
print (f" {ca tego ry }
print(" Orig ina l D a ta:")
print( df)
print(" Orig ina l D a ta withEn co din g :")
print( df)
print("M a pping o fEnco ded La bel s:")
print(la bel_ ma pp ing )
Example:
print(" One
print(o ne_ ho t_en co ded_ df)
print(" One
print(o ne_ ho t_en co ded_ df)
print(" One
Unit II - Advance Python Program: Q&A Extract
print(o ne_ ho t_en co ded_ df)
print(" One
print(o ne_ ho t_en co ded_ df)