NumPy: Create an 1-D array of 20 elements
Reshape 1D array to 2D and restore.
Write a NumPy program to create an 1-D array of 20 elements. Now create a new array of shape (5, 4) from the said array, then restores the reshaped array into a 1-D array.
Sample Solution:
Python Code:
# Importing NumPy library
import numpy as np
# Creating a NumPy array using arange with values from 0 to 40 (exclusive) with a step of 2
array_nums = np.arange(0, 40, 2)
# Printing the original array
print("Original array:")
print(array_nums)
# Reshaping the array into a new shape (5 rows and 4 columns)
print("\nNew array of shape(5, 4):")
new_array = array_nums.reshape(5, 4)
print(new_array)
# Flattening the reshaped array back into a 1-D array
print("\nRestore the reshaped array into a 1-D array:")
print(new_array.flatten())
Sample Output:
Original array: [ 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38] New array of shape(5, 4): [[ 0 2 4 6] [ 8 10 12 14] [16 18 20 22] [24 26 28 30] [32 34 36 38]] Restore the reshaped array into a 1-D array: [ 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38]
Explanation:
In the above example -
array_nums = np.arange(0, 40, 2): This code creates a 1-dimensional NumPy array containing even numbers from 0 to 38 (including 0 and excluding 40, with a step of 2).
new_array = array_nums.reshape(5, 4): This code reshapes the 1-dimensional array into a 2-dimensional array with 5 rows and 4 columns.
print(new_array.flatten()): This code flattens the 2-dimensional array back into a 1-dimensional array by concatenating its rows, and then prints the result.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics