w3resource

How to reshape and modify a 1D NumPy array to a 3x3 matrix?


9. 1D to 2D Shared Data

Write a NumPy program that creates a 1D array of 9 elements and reshape it into a 3x3 matrix. Modify the matrix and observe the changes in the original array.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D array of 9 elements
array_1d = np.arange(1, 10)

# Reshape the 1D array into a 3x3 matrix
matrix_3x3 = array_1d.reshape(3, 3)

# Modify the matrix
matrix_3x3[0, 0] = 99

# Print the modified matrix
print("Modified matrix:\n", matrix_3x3)

# Print the original 1D array to observe changes
print("Original 1D array after modification:", array_1d)

Output:

Modified matrix:
 [[99  2  3]
 [ 4  5  6]
 [ 7  8  9]]
Original 1D array after modification: [99  2  3  4  5  6  7  8  9]

Explanation:

  • Import NumPy library: We start by importing the NumPy library to handle array operations.
  • Create a 1D array: We create a 1D array array_1d with 9 elements using np.arange(1, 10).
  • Reshape to a 3x3 matrix: We reshape the 1D array to a 3x3 matrix matrix_3x3 using reshape().
  • Modify the matrix: We change the first element of the matrix to 99.
  • Print the modified matrix: We print the modified matrix to see the change.
  • Observe changes in the original array: We print the original 1D array to observe that the modification in the matrix also affects the original array since they share the same data.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to demonstrate the difference between reshape (view) and copy by modifying a 1D array reshaped to 2D.
  • Write a NumPy program to modify a reshaped 3×3 view of a 1D array and print both arrays to show data sharing.
  • Write a NumPy program to extract a sub-array from a reshaped 1D array and demonstrate how changes in the sub-array reflect on the original.
  • Write a NumPy program to compare the memory addresses of a 1D array and its 2D reshaped view to prove they share the same data.

Go to:


Previous: How to flatten a 3D NumPy array and print its Strides?
Next: How to change memory layout of a 2D NumPy array to C order?

Python-Numpy Code Editor:

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

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.