w3resource

NumPy: Create an 1-D array of 20 elements

NumPy: Array Object Exercise-175 with Solution

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:

import numpy as np
array_nums = np.arange(0, 40, 2)
print("Original array:")
print(array_nums)
print("\nNew array of shape(5, 4):")
new_array = array_nums.reshape(5, 4)
print(new_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]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}