arrayprogs
November 29, 2024
[1]: #---------------------------------------------------------------------------------------------
#numpy stddev
import numpy as np
# create a numpy array
marks = [Link]([76, 78, 81, 66, 85])
# compute the standard deviation of marks
std_marks = [Link](marks)
print("\n the standard deviation of marks : ")
print(std_marks)
# create a 2D array
array1 = [Link]([[2, 5, 9],
[3, 8, 11],
[4, 6, 7]])
# compute standard deviation along horizontal axis
result1 = [Link](array1, axis=1)
print("Standard deviation along horizontal axis:", result1)
# compute standard deviation along vertical axis
result2 = [Link](array1, axis=0)
print("Standard deviation along vertical axis:", result2)
# compute standard deviation of entire array
result3 = [Link](array1)
print("Standard deviation of entire array:", result3)
the standard deviation of marks :
6.368673331236263
Standard deviation along horizontal axis: [2.86744176 3.29983165 1.24721913]
Standard deviation along vertical axis: [0.81649658 1.24721913 1.63299316]
Standard deviation of entire array: 2.7666443551086073
1
[5]: #---------------------------------------------------------------------------------------------
#numpyrand
#rand in numpy
import numpy as np
from numpy import random
x = [Link](100)
print("\n Random integer from 0 to 100 ")
print(x)
#Generate a random float from 0 to 1:
x = [Link]()
print("\n Random float from 0 to 1 ")
print(x)
#randomly constructing 2D array
array = [Link](3, 2)
print("\n 3X2 Array filled with random float values : \n", array);
#The choice() method allows you to generate a random value based on an array of␣
↪values.
#The choice() method takes an array as a parameter and randomly returns one of␣
↪the values.
x = [Link]([3, 5, 7, 9])
print("\n Random integer from array elements ")
print(x)
#Generate a 2-D array that consists of the values in the array parameter (3, 5,␣
↪7, and 9)
x = [Link]([3, 5, 7, 9], size=(3, 5))
print("\n 3X5 Array filled with random integer from array elements : \n")
print(x)
#The shuffle() method takes a sequence, like a list
mylist = ["apple", "banana", "cherry", "orange"]
[Link](mylist)
print("\n Shuffled list ")
print(mylist)
#permutation() Generate a random permutation of elements of following array
arr = [Link]([1, 2, 3, 4, 5])
print("\n random permutation of elements ")
print([Link](arr))
#Set the seed() value to 10
2
[Link](10)
print("\n seed() output")
print([Link](4))
Random integer from 0 to 100
89
Random float from 0 to 1
0.5833217369377363
3X2 Array filled with random float values :
[[-0.90561048 -0.89808938]
[ 0.45187984 -0.85947418]
[-0.53479453 1.03287114]]
Random integer from array elements
3
3X5 Array filled with random integer from array elements :
[[9 7 7 5 3]
[3 7 5 9 7]
[5 5 5 9 5]]
Shuffled list
['orange', 'apple', 'banana', 'cherry']
random permutation of elements
[4 3 5 1 2]
seed() output
[0.77132064 0.02075195 0.63364823 0.74880388]
[37]: #---------------------------------------------------------------------------------------------
#numpy percentile
import numpy as np
# create an array
array1 = [Link]([1, 3, 5, 7, 9, 11, 13, 15, 17, 19])
# compute the 25th percentile of the array
result1 = [Link](array1, 25)
print("25th percentile:",result1)
3
# compute the 75th percentile of the array
result2 = [Link](array1, 75)
print("75th percentile:",result2)
'''
Here,
25% of the values in array1 are less than or equal to 5.5.
75% of the values in array1 are less than or equal to 14.5.'''
25th percentile: 5.5
75th percentile: 14.5
[37]: '\nHere,\n\n25% of the values in array1 are less than or equal to 5.5.\n75% of
the values in array1 are less than or equal to 14.5.'
[9]: #---------------------------------------------------------------------------------------------
#numpyminmax
import numpy as np
# create an array
array1 = [Link]([2,6,9,15,17,22,65,1,62])
# find the minimum value of the array
min_val = [Link](array1)
# find the maximum value of the array
max_val = [Link](array1)
# print the results
print("Minimum value:", min_val)
print("Maximum value:", max_val)
Minimum value: 1
Maximum value: 65
[11]: #---------------------------------------------------------------------------------------------
#numpymedian
import numpy as np
# create a 1D array with 5 elements
array1 = [Link]([1, 2, 3, 4, 5])
# calculate the median in case of odd number of elements
median = [Link](array1)
4
print("\n Median for odd number of elements : ")
print(median)
array1 = [Link]([1, 2, 3, 4, 5, 6])
# calculate the median in case of even number of elements
median = [Link](array1)
print("\n Median for even number of elements : ")
print(median)
print("\n\n **********Median of NumPy 2D Array *******")
'''
If we specify,
axis = 0, median is calculated along vertical axis
axis = 1, median is calculated along horizontal axis '''
# create a 2D array
array1 = [Link]([[2, 4, 6],
[8, 10, 12],
[14, 16, 18]])
# compute median along horizontal axis
result1 = [Link](array1, axis=1)
print("Median along horizontal axis :", result1)
# compute median along vertical axis
result2 = [Link](array1, axis=0)
print("Median along vertical axis:", result2)
# compute median of entire array
result3 = [Link](array1)
print("Median of entire array:", result3)
Median for odd number of elements :
3.0
Median for even number of elements :
3.5
**********Median of NumPy 2D Array *******
Median along horizontal axis : [ 4. 10. 16.]
5
Median along vertical axis: [ 8. 10. 12.]
Median of entire array: 10.0
[13]: #---------------------------------------------------------------------------------------------
#numpymean
import numpy as np
# create a numpy array
marks = [Link]([76, 78, 81, 66, 85])
# compute the mean of marks
mean_marks = [Link](marks)
print("\n Mean of entire array:")
print(mean_marks)
# create a 2D array
array1 = [Link]([[1, 3],
[5, 7]])
# calculate the mean of the entire array
result1 = [Link](array1)
print("Entire Array:",result1)
# calculate the mean along vertical axis (axis=0)
result2 = [Link](array1, axis=0)
print("Along Vertical Axis:",result2)
# calculate the mean along (axis=1)
result3 = [Link](array1, axis=1)
print("Along Horizontal Axis :",result3)
Mean of entire array:
77.2
Entire Array: 4.0
Along Vertical Axis: [3. 5.]
Along Horizontal Axis : [2. 6.]
[15]: #---------------------------------------------------------------------------------------------
#numpyarraysaveloadnpy
#Save/Load Single NumPy Array in text File
import numpy as np
array1 = [Link]([[2, 4, 6],
6
[8, 10, 12]])
# save the array to a file
[Link]('[Link]', array1)
print("\n Array Saved...")
# load the saved NumPy array
loaded_array = [Link]('[Link]')
print("\n Array Loaded...")
# display the loaded array
print(loaded_array)
Array Saved…
Array Loaded…
[[ 2 4 6]
[ 8 10 12]]
[17]: #---------------------------------------------------------------------------------------------
#numpyarraysaveloadbinary
#Save/Load Single NumPy Array in text File
import numpy as np
array1 = [Link]([[2, 4, 6],
[8, 10, 12]])
# save the array to a file
[Link]('[Link]', array1)
print("\n Array Saved...")
# load the saved NumPy array
loaded_array = [Link]('[Link]')
print("\n Array Loaded...")
# display the loaded array
print(loaded_array)
Array Saved…
Array Loaded…
[[ 2 4 6]
[ 8 10 12]]
7
[19]: #---------------------------------------------------------------------------------------------
#numpyarraysaveload
#Save/Load Single NumPy Array in text File
import numpy as np
# create an array
array1 = [Link]([[1, 3, 5], [2, 4, 6]])
# save the array to a text file
[Link]('[Link]', array1)
print("\n Array Saved...")
# load the data from the text file
loaded_data = [Link]('[Link]')
print("\n Array Loaded...")
# print the loaded data
print(loaded_data)
Array Saved…
Array Loaded…
[[1. 3. 5.]
[2. 4. 6.]]
[23]: #---------------------------------------------------------------------------------------------
#arraysplitting
# Python program to demonstrate splitting in numpy
import numpy as np
#Split the array in 3 parts
arr = [Link]([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print("\n\n Splitting the array in 3 parts ")
print(newarr)
#Split the array in 4 parts
arr = [Link]([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 4)
print("\n\n Splitting the array in 4 parts ")
print(newarr)
8
print("\n *******************Splitting 2-D Arrays **************************")
#Split the 2-D array into three 2-D arrays.
arr = [Link]([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print("\n\n Splitting the array into three 2-D arrays ")
print(newarr)
#Split the 2-D array into three 2-D arrays.
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15],␣
↪[16, 17, 18]])
newarr = np.array_split(arr, 3)
print("\n\n Splitting the array into three 2-D arrays ")
print(newarr)
#Use the hsplit() method to split the 2-D array into three 2-D arrays along␣
↪rows.
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15],␣
↪[16, 17, 18]])
newarr = [Link](arr, 3)
print("\n After splitting the 2-D array into three 2-D arrays along rows")
print(newarr)
#Use the vsplit() method to split the 2-D array into three 2-D arrays along␣
↪rows.
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15],␣
↪[16, 17, 18]])
newarr = [Link](arr, 3)
print("\n After splitting the 2-D array into three 2-D arrays along Columns")
print(newarr)
#Use the dsplit() method to split the 3-D array into 2 arrays along depth.
arr = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
newarr = [Link](arr, 2)
print("\n After splitting the 2-D array into three 2-D arrays along depth")
print(newarr)
newarr = [Link](arr, 2)
print("\n After splitting the 2-D array into three 2-D arrays along rows")
print(newarr)
newarr = [Link](arr, 2)
print("\n After splitting the 2-D array into three 2-D arrays along Columns")
print(newarr)
Splitting the array in 3 parts
[array([1, 2]), array([3, 4]), array([5, 6])]
9
Splitting the array in 4 parts
[array([1, 2]), array([3, 4]), array([5]), array([6])]
*******************Splitting 2-D Arrays **************************
Splitting the array into three 2-D arrays
[array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]]), array([[ 9, 10],
[11, 12]])]
Splitting the array into three 2-D arrays
[array([[1, 2, 3],
[4, 5, 6]]), array([[ 7, 8, 9],
[10, 11, 12]]), array([[13, 14, 15],
[16, 17, 18]])]
After splitting the 2-D array into three 2-D arrays along rows
[array([[ 1],
[ 4],
[ 7],
[10],
[13],
[16]]), array([[ 2],
[ 5],
[ 8],
[11],
[14],
[17]]), array([[ 3],
[ 6],
[ 9],
[12],
[15],
[18]])]
After splitting the 2-D array into three 2-D arrays along Columns
[array([[1, 2, 3],
[4, 5, 6]]), array([[ 7, 8, 9],
[10, 11, 12]]), array([[13, 14, 15],
[16, 17, 18]])]
After splitting the 2-D array into three 2-D arrays along depth
[array([[[1],
[3]],
10
[[5],
[7]]]), array([[[2],
[4]],
[[6],
[8]]])]
After splitting the 2-D array into three 2-D arrays along rows
[array([[[1, 2]],
[[5, 6]]]), array([[[3, 4]],
[[7, 8]]])]
After splitting the 2-D array into three 2-D arrays along Columns
[array([[[1, 2],
[3, 4]]]), array([[[5, 6],
[7, 8]]])]
[25]: #---------------------------------------------------------------------------------------------
#Arrayslicing
#Save/Load Single NumPy Array in text File
# Python program to demonstrate slicing in numpy
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7])
print("\n\n Slice elements from index 1 to index 5 ")
print(arr[1:5])
print("\n\n Slice elements from index 4 to the end of the array ")
print(arr[4:])
print("\n\n Slice elements from the beginning to index 4 (not included) ")
print(arr[:4])
print("\n\n Slice from the index 3 from the end to index 1 from the end ")
print(arr[-3:-1])
print("\n\n **Slice from the index 3 from the end to index 1 from the end ")
print(arr[-3:])
print("\n\n Slice every other element from index 1 to index 5 ")
11
print(arr[Link])
print("\n\n Slice every other element from the entire array ")
print(arr[::2])
print("\n *******************Slicing 2-D Arrays **************************")
arr = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print("\n\n From the second element, slice elements from index 1 to index 4␣
↪(not included) ")
#Remember that second element has index 1.
print(arr[1, 1:4])
print("\n\n From both elements, return index 2 ")
print(arr[0:2, 2])
print("\n\n From both elements, slice index 1 to index 4 (not included), this␣
↪will return a 2-D array ")
print(arr[0:2, 1:4])
Slice elements from index 1 to index 5
[2 3 4 5]
Slice elements from index 4 to the end of the array
[5 6 7]
Slice elements from the beginning to index 4 (not included)
[1 2 3 4]
Slice from the index 3 from the end to index 1 from the end
[5 6]
**Slice from the index 3 from the end to index 1 from the end
[5 6 7]
Slice every other element from index 1 to index 5
[2 4]
12
Slice every other element from the entire array
[1 3 5 7]
*******************Slicing 2-D Arrays **************************
From the second element, slice elements from index 1 to index 4 (not included)
[7 8 9]
From both elements, return index 2
[3 8]
From both elements, slice index 1 to index 4 (not included), this will return a
2-D array
[[2 3 4]
[7 8 9]]
[27]: #---------------------------------------------------------------------------------------------
#array reshping
#Array Reshaping
#Convert the following 1-D array with 12 elements into a 2-D array.
#The outermost dimension will have 4 arrays, each with 3 elements:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](4, 3)
print("\n\n 1-D array with 12 elements into a 2-D array \n")
print(newarr)
#Convert the following 1-D array with 12 elements into a 3-D array.
#The outermost dimension will have 2 arrays that contains 3 arrays, each with 2␣
↪elements:
newarr = [Link](2, 3, 2)
print("\n\n 1-D array with 12 elements into a 3-D array \n")
print(newarr)
'''Unknown Dimension
You are allowed to have one "unknown" dimension.
13
Meaning that you do not have to specify an exact number for one of the␣
↪dimensions in the reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.'''
#Convert 1D array with 8 elements to 3D array with 2x2 elements:
newarr = [Link](2, 2, -1)
print("\n\n 1-D array with 8 elements into a 3-D array \n")
print(newarr)
'''
Flattening the arrays
Flattening array means converting a multidimensional array into a 1D array.
We can use reshape(-1) to do this.'''
arr = [Link]([[1, 2, 3], [4, 5, 6]])
newarr = [Link](-1)
print("\n\n Flattened array \n")
print(newarr)
1-D array with 12 elements into a 2-D array
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
1-D array with 12 elements into a 3-D array
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]
1-D array with 8 elements into a 3-D array
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
14
Flattened array
[1 2 3 4 5 6]
[29]: #Arrayindexing
import numpy as np
arr = [Link]([1, 2, 3, 4])
print("\n\n Get the first element \n")
print(arr[0])
print("\n\n Get the second element \n")
print(arr[1])
print("\n\n Get additon of the third element and fourth element \n")
print(print(arr[2] + arr[3]))
print("\n\n ****************2D Array Indexing **************")
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print("\n\n Access the element on the first row, second column \n")
print('2nd element on 1st row: ', arr[0, 1])
print('5th element on 2nd row: ', arr[1, 4])
print("\n\n ****************3D Array Indexing **************")
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("\n\n Access the third element of the second array of the first array \n")
print(arr[0, 1, 2])
'''
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
The second number represents the second dimension, which also contains two␣
↪arrays:
[1, 2, 3]
15
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6
'''
arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print("\nPrint the last element from the 2nd dimension \n")
print('Last element from 2nd dim: ', arr[1, -1])
arr = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr[1, 1, 0])
Get the first element
Get the second element
Get additon of the third element and fourth element
7
None
****************2D Array Indexing **************
Access the element on the first row, second column
2nd element on 1st row: 2
5th element on 2nd row: 10
****************3D Array Indexing **************
16
Access the third element of the second array of the first array
Print the last element from the 2nd dimension
Last element from 2nd dim: 10
7
[31]: #ARRAY CREATION
# Python program to demonstrate
# array creation techniques
import numpy as np
# Creating array from list with type float
a = [Link]([[1, 2, 4], [5, 8, 7]], dtype='float')
print("Array created using passed list:\n", a)
# Creating array from tuple
b = [Link]((1, 3, 2))
print("\nArray created using passed tuple:\n", b)
# Creating a 3X4 array with all zeros
c = [Link]((3, 4))
print("\nAn array initialized with all zeros:\n", c)
# Create a constant value array of complex type
d = [Link]((3, 3), 6, dtype='complex')
print("\nAn array initialized with all 6s."
"Array type is complex:\n", d)
# Python program to demonstrate
# basic array characteristics
import numpy as np
# Creating array object
arr = [Link]([[1, 2, 3],
[4, 2, 5]])
print("Array is \n: ", arr)
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
17
print("No. of dimensions: ", [Link])
# Printing shape of array
print("Shape of array: ", [Link])
# Printing size (total number of elements) of array
print("Size of array: ", [Link])
# Printing type of elements in array
print("Array stores elements of type: ", [Link])
Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]
Array created using passed tuple:
[1 3 2]
An array initialized with all zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized with all [Link] type is complex:
[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]
Array is
: [[1 2 3]
[4 2 5]]
Array is of type: <class '[Link]'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int32
[33]: #Array concatenation1
#Array Concatenation1
# importing numpy as np
import numpy as np
arr1 = [Link]([[[1, 2], [3, 4]],[[5, 6],[7,8]]])
arr2 = [Link]([[[9, 10], [11, 12]],[[13, 14],[15,16]]])
#Concatenating along rows
gfg = [Link]((arr1, arr2), axis = 0)
print("\n\n Concatenating along rows (axis=0)")
18
print (gfg)
#Concatenating along Columnss
gfg = [Link]((arr1, arr2), axis = 1)
print("\n\n Concatenating along columns (axis=1)")
print (gfg)
#Concatenating as flattened array
gfg = [Link]((arr1, arr2), axis = None)
print("\n\n Concatenating as flattened array")
print (gfg)
print ("\n **************** stack() demo *******")
arr1 = [Link]([[[1, 2], [3, 4]],[[5, 6],[7,8]]])
arr2 = [Link]([[[9, 10], [11, 12]],[[13, 14],[15,16]]])
arr = [Link]((arr1, arr2), axis=1)
print("\n\n Concatenation using stack()")
print(arr)
#hstack() to stack along rows.
arr = [Link]((arr1, arr2))
print("\n\n Horizontal Stacking using hstack()")
print(arr)
#vstack() to stack along Columns.
arr = [Link]((arr1, arr2))
print("\n\n Vertical Stacking using vstack()")
print(arr)
Concatenating along rows (axis=0)
[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]
[[13 14]
[15 16]]]
19
Concatenating along columns (axis=1)
[[[ 1 2]
[ 3 4]
[ 9 10]
[11 12]]
[[ 5 6]
[ 7 8]
[13 14]
[15 16]]]
Concatenating as flattened array
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
**************** stack() demo *******
Concatenation using stack()
[[[[ 1 2]
[ 3 4]]
[[ 9 10]
[11 12]]]
[[[ 5 6]
[ 7 8]]
[[13 14]
[15 16]]]]
Horizontal Stacking using hstack()
[[[ 1 2]
[ 3 4]
[ 9 10]
[11 12]]
[[ 5 6]
[ 7 8]
[13 14]
[15 16]]]
Vertical Stacking using vstack()
[[[ 1 2]
[ 3 4]]
20
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]
[[13 14]
[15 16]]]
[35]: #ARRAY CONCATENATION
#Array Concatenation
# importing numpy as np
import numpy as np
arr1 = [Link]([[2, 4], [6, 8]])
arr2 = [Link]([[3, 5], [7, 9]])
#Concatenating along rows
gfg = [Link]((arr1, arr2), axis = 0)
print("\n\n Concatenating along rows (axis=0)")
print (gfg)
#Concatenating along Columnss
gfg = [Link]((arr1, arr2), axis = 1)
print("\n\n Concatenating along columns (axis=1)")
print (gfg)
#Concatenating as flattened array
gfg = [Link]((arr1, arr2), axis = None)
print("\n\n Concatenating as flattened array")
print (gfg)
print ("\n **************** stack() demo *******")
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2), axis=1)
print("\n\n Concatenation using stack()")
print(arr)
#hstack() to stack along rows.
arr = [Link]((arr1, arr2))
print("\n\n Horizontal Stacking using hstack()")
print(arr)
21
#vstack() to stack along Columns.
arr = [Link]((arr1, arr2))
print("\n\n Vertical Stacking using vstack()")
print(arr)
Concatenating along rows (axis=0)
[[2 4]
[6 8]
[3 5]
[7 9]]
Concatenating along columns (axis=1)
[[2 4 3 5]
[6 8 7 9]]
Concatenating as flattened array
[2 4 6 8 3 5 7 9]
**************** stack() demo *******
Concatenation using stack()
[[1 4]
[2 5]
[3 6]]
Horizontal Stacking using hstack()
[1 2 3 4 5 6]
Vertical Stacking using vstack()
[[1 2 3]
[4 5 6]]
[ ]:
22