w3resource

NumPy: Create an 1-D array of 20 elements

NumPy: Array Object Exercise-175 with Solution

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:

Previous: Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array.
Next: Write a NumPy program to create an array of 4,5 shape and swap column1 with column4.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-175.php