w3resource

Shifting all elements in a 4x4 array to the right using NumPy

NumPy: Advanced Exercise-31 with Solution

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

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 to the right
shifted_array = np.roll(array, shift=1, axis=1)

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

Output:

Original Array:
 [[0.56244965 0.13649834 0.11747523 0.32500712]
 [0.70083542 0.82382861 0.30299759 0.91059768]
 [0.94215098 0.40837075 0.02121122 0.90121581]
 [0.34578054 0.22681019 0.67214344 0.58693076]]
Array after shifting all elements one position to the right:
 [[0.32500712 0.56244965 0.13649834 0.11747523]
 [0.91059768 0.70083542 0.82382861 0.30299759]
 [0.90121581 0.94215098 0.40837075 0.02121122]
 [0.58693076 0.34578054 0.22681019 0.67214344]]

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 Right: Use np.roll with shift=1 and axis=1 to shift all elements one position to the right.
  • Print the Shifted Array: Print the array after shifting all elements one position to the right.

Python-Numpy Code Editor:

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

Previous: Rotating a 4x4 array 90 degrees Counterclockwise using NumPy.
Next: Shifting all elements in a 4x4 array downwards 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://www.w3resource.com/python-exercises/numpy/advanced-numpy-exercise-31.php