w3resource

Rotating a 4x4 array 90 degrees Counterclockwise using NumPy

NumPy: Advanced Exercise-30 with Solution

Write a NumPy program to create a 4x4 array with random values and rotate the array 90 degrees counterclockwise.

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)

# Rotate the array 90 degrees counterclockwise
rotated_array = np.rot90(array)

# Print the rotated array
print("Array after 90 degrees counterclockwise rotation:\n", rotated_array)

Output:

Original Array:
 [[0.16774949 0.30263452 0.75987069 0.368299  ]
 [0.39865392 0.4344374  0.29780849 0.07469577]
 [0.94042863 0.37602418 0.36429796 0.76098639]
 [0.43534721 0.52836575 0.65394788 0.47563204]]
Array after 90 degrees counterclockwise rotation:
 [[0.368299   0.07469577 0.76098639 0.47563204]
 [0.75987069 0.29780849 0.36429796 0.65394788]
 [0.30263452 0.4344374  0.37602418 0.52836575]
 [0.16774949 0.39865392 0.94042863 0.43534721]]

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.
  • Rotate the Array: Use np.rot90 to rotate the array 90 degrees counterclockwise.
  • Print the Rotated Array: Print the array after rotating it 90 degrees counterclockwise.

Python-Numpy Code Editor:

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

Previous: Swapping the first and last rows of a 4x4 array using NumPy.
Next: Shifting all elements in a 4x4 array to the right using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.