Reshaping and Stacking
Reshaping and stacking NumPy
arrays involve modifying the shape or size of an array or amalgamating multiple arrays into a single array. NumPy
offers a variety of functions for these purposes, such as:
reshape()
: Alters an array to a new shape without changing its data;resize()
: Changes an array's size to a new shape, which can lead to the addition or removal of elements;vstack()
: Vertically stacks arrays (row-wise) to form a single array;hstack()
: Horizontally stacks arrays (column-wise) to create a single array;concatenate()
: Joins arrays along a specified axis;stack()
: Layers arrays along a new axis, adding a dimension.
Tarefa
Swipe to start coding
- Reshape the
arr
array to a new configuration. - Resize the
arr
array to a new dimension, possibly adding or omitting elements. - Vertically stack all the arrays to produce a unified array (in the order of creation).
- Horizontally stack all the arrays to form a single array (in the order of creation).
Solução
import numpy as np
# Create a NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr_1 = np.array([[7, 8, 9], [10, 11, 12]])
arr_2 = np.array([[13, 14, 15], [16, 17, 18]])
# Reshape the array to a new shape
reshaped_arr = arr.reshape(3, 2)
# Resize the array to a new shape, potentially adding or removing elements
resized_arr = np.resize(arr, (4, 3))
# Stack the arrays vertically (row-wise) to create a single array
vertical_stack = np.vstack((arr, arr_1, arr_2))
# Stack the arrays horizontally (column-wise) to create a single array
horizontal_stack = np.hstack((arr, arr_1, arr_2))
display(reshaped_arr, resized_arr, vertical_stack, horizontal_stack)
Mark tasks as Completed
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 1. Capítulo 6
AVAILABLE TO ULTIMATE ONLY