NumPy: Create two arrays of size bigger and smaller than a given array
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:
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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to resize a given array to a smaller shape using np.resize and verify the result.
- Create a function that pads an array to a larger size with repeating elements or zeros.
- Test the resizing operation on a 2D array and ensure that data is preserved or repeated appropriately.
- Implement a solution that compares the output of np.resize with reshaping followed by padding.
Go to:
PREV : Index of Sliced Elements in Array
NEXT : Broadcast Two Arrays (Shape (3,3) + (3))
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.