NumPy: Create two arrays of size bigger and smaller than a given array
NumPy: Array Object Exercise-123 with Solution
Resize Array to Bigger and Smaller Sizes
Write a NumPy program to create two arrays bigger and smaller than a given array.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a 4x4 array 'x' with elements from 0 to 15 using np.arange() and reshaping it to a 4x4 array
x = np.arange(16).reshape(4, 4)
# Printing a message indicating the original array will be displayed
print("Original array:")
# Displaying the original 4x4 array 'x'
print(x)
# Printing a message indicating the creation of a 2x2 array from the original array
print("\nArray with size 2x2 from the original array:")
# Creating a new 2x2 array 'new_array1' using np.resize() from the original array 'x'
new_array1 = np.resize(x, (2, 2))
# Displaying the new 2x2 array 'new_array1'
print(new_array1)
# Printing a message indicating the creation of a 6x6 array from the original array
print("\nArray with size 6x6 from the original array:")
# Creating a new 6x6 array 'new_array2' using np.resize() from the original array 'x'
# The elements will be repeated if necessary to fill the new size
new_array2 = np.resize(x, (6, 6))
# Displaying the new 6x6 array 'new_array2'
print(new_array2)
Sample Output:
Original arrays: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Array with size 2x2 from the said array: [[0 1] [2 3]] Array with size 6x6 from the said array: [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11] [12 13 14 15 0 1] [ 2 3 4 5 6 7] [ 8 9 10 11 12 13] [14 15 0 1 2 3]]
Explanation:
x = np.arange(16).reshape(4, 4): Create a 1D NumPy array of integers from 0 to 15 using np.arange(16), and then reshape it into a 4x4 2D array using np.reshape().
new_array1 = np.resize(x, (2, 2)): Resize the 4x4 2D array x to a 2x2 2D array using np.resize(). The function takes the input array and the desired shape as arguments.
new_array2 = np.resize(x, (6, 6)): Resize the 4x4 2D array x to a 6x6 2D array using np.resize().
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to join a sequence of arrays along a new axis.
Next: Write a NumPy program to broadcast on different shapes of arrays where p(3,3) + q(3).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-123.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics