Expt 18
Expt 18
Date of Performance:
Date of Submission:
PROBLEM DEFINITION:
Develop a Python program to create a 1D, 2D and 3D NumPy array. Perform basic
operations like reshaping, slicing, and indexing.
SOURCE CODE:
# Create a 1D array
import numpy as np
Output:
[1, 2, 3, 4, 5]
# Create a 2D array
import numpy as np
# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Original 2D array:")
print(array_2d)
Output:
Original 2D array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reshaped 3D array:
[[[1]
[2]
[3]]
[[4]
[5]
[6]]
[[7]
[8]
[9]]]
# Create a 3D array
#importing the package numpy as pynum
import numpy as pynum
#creating a three dimensional array using the array function and storing it in the variable called
threedimarray
threedimarray = pynum.array([[[10,20,30,40], [50,60,70,80]]])
#displaying the elements of the newly created three dimensional array followed by an one line
space
print 'The elements of the newly created three-dimensional array are:'
print '\n'
print threedimarray
print '\n'
Output:
# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print("Original 2D array:")
print(array_2d)
print("\nReshaped 3D array:")
print(array_3d)
Output:
Original 2D array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Reshaped 3D array:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Output:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
Output:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])
Output:
#indexing in array
import numpy as np
array1 = np.arange(0,10)
array1
Output:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
CONCLUSION:
Reshaping arrays is a fundamental operation in NumPy, and it allows you to manipulate data in
various ways. Reshaping a 2D array into a 3D array can be useful for representing data with an
additional dimension, such as depth or volume. Additionally, reshaping a flattened array into a
3D array can help organize data into a structured format. By understanding how to reshape
arrays, you can effectively work with multidimensional data in NumPy.
R1 R2 R3 R4 Total Signature