w3resource

Shifting all elements in a 4x4 array downwards using NumPy

NumPy: Advanced Exercise-32 with Solution

Write a NumPy program to create a 4x4 array with random values and shift all elements one position downwards.

This NumPy program involves creating a 4x4 array filled with random values. Then, it shifts all elements one position downwards, effectively moving each element to the row below it and wrapping around any elements at the bottom of a column to the top of the next column. This operation essentially shifts the entire array downwards by one row.

Sample Solution:

Python Code:

import numpy as np

# Create a 4x4 array with random values
array = np.random.random((4, 4))

# Print the original array
print("Original Array:\n", array)

# Shift all elements one position downwards
shifted_array = np.roll(array, shift=1, axis=0)

# Print the shifted array
print("Array after shifting all elements one position downwards:\n", shifted_array)

Output:

Original Array:
 [[0.57511189 0.40488217 0.14815589 0.25081063]
 [0.73184136 0.67798233 0.04999228 0.84180437]
 [0.24519195 0.7816562  0.83331184 0.84790648]
 [0.90689699 0.30199631 0.76573246 0.30176562]]
Array after shifting all elements one position downwards:
 [[0.90689699 0.30199631 0.76573246 0.30176562]
 [0.57511189 0.40488217 0.14815589 0.25081063]
 [0.73184136 0.67798233 0.04999228 0.84180437]
 [0.24519195 0.7816562  0.83331184 0.84790648]]

Explanation:

  • Import NumPy: Import the NumPy library to work with arrays.
  • Create a Random 4x4 Array: Generate a 4x4 array filled with random values using np.random.random.
  • Print the Original Array: Print the original 4x4 array for reference.
  • Shift Elements Downwards: Use np.roll with shift=1 and axis=0 to shift all elements one position downwards.
  • Print the Shifted Array: Print the array after shifting all elements one position downwards.

Python-Numpy Code Editor:

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

Previous: Shifting all elements in a 4x4 array to the right using NumPy.
Next: Calculating Pairwise Euclidean distances in a 3x3 array using NumPy.

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://w3resource.com/python-exercises/numpy/advanced-numpy-exercise-32.php