You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
22 Hrs
31 Min
7 Seg

Transformación de Arrays: Reshape y Manipulación

8/32
Resources

Learning to transpose and transform arrays, invert arrays and flatten multidimensional arrays are essential skills for handling large volumes of data and performing complex calculations efficiently. Using the NumPy library in Python, these operations are not only easy to implement but also highly optimized for working with large data sets.

Matrix Transpose

The transpose of a matrix is an operation that swaps its rows and columns, essential in linear algebra and scientific data manipulation. In NumPy, you can transpose a matrix using matrix.T, which converts rows into columns and vice versa.

import numpy as npmatrix = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) transposed_matrix = matrix.Tprint("Original matrix:\n", matrix)print("Transposed matrix:\n", transposed_matrix)

Changing the Shape (Reshape) of an Array

The reshape function allows you to change the shape of an array without changing its data. It is important to make sure that the total number of elements remains constant.

For example, an array of 12 elements can be reshaped into a 3x4, 4x3, 2x6, etc. array, but not into a 5x3 array.

# Create an array with the numbers 1 to 12array = np.arange(1, 13)# Change the shape of the array to a 3-row, 4-column arrayreshaped_array = array.reshape(3, 4) print("Original array:", array) print("Array reshaped to 3x4:\n", reshaped_array)
  • np.arange(1, 13) creates a one-dimensional array of 12 elements.
  • array.reshape(3, 4) reshapes this array into a 3-row, 4-column array. The total number of elements (12) must be the same before and after reshaping.

Make sure that the total number of elements in the new shape matches the total number of elements in the original array. Otherwise, a ValueError will occur .

How is an array inverted in NumPy?

In signal processing and data inversion algorithms, it is very common to invert an array, which involves changing the order of its elements so that the first element becomes the last and vice versa.

# Create an array with the numbers 1 to 5array = np.array([1, 2, 3, 4, 5]) # Invert the arrayreversed_array = array[::-1]print("Original array:", array)print("Reversed array:", reversed_array)

array[::-1] Reverses the array using slicing. array[start:stop:step] is the general notation for slicing in Python, where start is the initial index, stop is the final (excluded) index, and step is the step size. By omitting start and stop and using 1 as step, you get a copy of the array in reverse order.

You should always make sure that the start, stop, and step indexes are set correctly to avoid indexing errors.

Flattening Multidimensional Arrays

Array flattening is the process of converting a multidimensional array into a one-dimensional array, useful in algorithms that require linear input or for aggregation operations. In NumPy, you can flatten an array using flatten().

 # Create a 2Darray multi_array = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) # Flatten the 2Darray to 1Dflattened_array = multi_array.flatten()print("Multidimensional array:\n", multi_array)print("Flattened array:", flattened_array)

multi_array.flatten() converts a 2D array into a 1D array, essentially "flattening" the multidimensional structure. This is useful for algorithms that require one-dimensional input or to facilitate aggregation operations.

The flatten() operation always creates a copy, so you should make sure this is what you want to avoid memory problems.

Contributions 9

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Estos procesos, **reshape** y **manipulación de arrays,** permiten que los datos se preparen correctamente para que la red neuronal pueda extraer patrones y hacer predicciones con precisión. Sin **reshape** y **manipulación de arrays**, no sería posible aplicar redes neuronales a una amplia variedad de problemas de datos estructurados o no estructurados.
![](https://static.platzi.com/media/user_upload/image-8a1d9979-fc7d-4c97-8530-bc1ffa1937b5.jpg)
Me encanto la conceptualización final que da Carli sobre el uso para redes neuronales.
#### **1. TRANSPOSICIÓN DE MATRICES** **Descripción:** La transposición de matrices en Numpy reorganiza las filas y columnas de un arreglo 2D. El atributo .T invierte la matriz a lo largo de su diagonal, intercambiando filas por columnas. **Ejemplos:** **Código:** matrix = np.array(\[\[1, 2, 3], \[4, 5, 6], \[7, 8, 9]]) transposed\_matrix = matrix.T print(matrix) print(transposed\_matrix)  **Resultado:** matrix:  \[\[1 2 3]  \[4 5 6]  \[7 8 9]] transposed\_matrix:  \[\[1 4 7]  \[2 5 8]  \[3 6 9]] *  **Explicación:** Las filas de la matriz original se convierten en las columnas de la matriz transpuesta, y viceversa. #### **2. RESHAPE** **Descripción:** La función reshape en Numpy permite cambiar la forma de un arreglo sin alterar sus datos. El número total de elementos debe permanecer constante. **Ejemplos:** **RESHAPE VÁLIDO:**array = np.arange(1, 13) reshaped\_array = array.reshape(3, 4) print(array) print(reshaped\_array)  **Resultado:** array: \[1 2 3 4 5 6 7 8 9 10 11 12] reshaped\_array: \[\[ 1  2  3  4]  \[ 5  6  7  8]  \[ 9 10 11 12]] *  **Explicación:** El arreglo 1D con 12 elementos se reconfigura en un arreglo 2D de 3x4. **RESHAPE INVÁLIDO:**array = np.arange(1, 15) reshaped\_array = array.reshape(3, 4)  **Resultado:** ValueError: cannot reshape array of size 14 into shape (3, 4) *  **Explicación:** La operación falla porque el número total de elementos (14) no es divisible por la forma deseada (3x4). #### **3. REVERSE** **Descripción:** Invertir un arreglo cambia su orden. En Numpy, se puede invertir un arreglo utilizando slicing con un paso de -1. **Ejemplos:** **Código:** array = np.arange(1, 13) reversed\_array = array\[::-1] print(array) print(reversed\_array)  **Resultado:** array: \[ 1  2  3  4  5  6  7  8  9 10 11 12] reversed\_array: \[12 11 10  9  8  7  6  5  4  3  2  1] *  **Explicación:** La operación de slicing con \[::-1] invierte el arreglo. #### **4. FLATTENING** **Descripción:** Flattening convierte un arreglo multidimensional en un arreglo unidimensional. El método .flatten() en Numpy lo logra. **Ejemplos:** **Código:** matrix = np.array(\[\[1, 2, 3], \[4, 5, 6], \[7, 8, 9]]) flattened\_array = matrix.flatten() print(matrix) print(flattened\_array)  **Resultado:** matrix:  \[\[1 2 3]  \[4 5 6]  \[7 8 9]] flattened\_array: \[1 2 3 4 5 6 7 8 9] *  **Explicación:** La matriz 2D se reduce a un arreglo 1D combinando todos los elementos por filas.
### Transpuesta La transpuesta de una matriz en NumPy se puede obtener utilizando el método `.T`. Este método intercambia las filas y columnas de la matriz original. Por ejemplo, si tienes una matriz `A`, su transpuesta se obtiene con `A.T`. ```js import numpy as np A = np.array([[1, 2, 3], [4, 5, 6]]) A_transpuesta = A.T print("Matriz original:\\\\n", A) print("Matriz transpuesta:\\\\n", A_transpuesta) ``` ### Reshape El método `reshape` de NumPy permite cambiar la forma de un array sin alterar sus datos. Por ejemplo, si tienes un array `B` de forma `(2, 3)`, puedes cambiarlo a una forma `(3, 2)` utilizando `B.reshape(3, 2)`. ```js B = np.array([[1, 2, 3], [4, 5, 6]]) B_reshaped = B.reshape(3, 2) print("Array original:\\\\\\\\n", B) print("Array reshaped:\\\\\\\\n", B_reshaped) ``` ### Flattening El método `flatten` de NumPy convierte un array multidimensional en un array unidimensional. Esto es útil cuando necesitas trabajar con datos en una forma lineal. Por ejemplo, si tienes un array `D` de forma `(2, 3)`, puedes aplanarlo utilizando `D.flatten()`. ```js D = np.array([[1, 2, 3], [4, 5, 6]]) D_flattened = D.flatten() print("Array original:\\\\n", D) print("Array aplanado:\\\\n", D_flattened) ```
### Ravel La función `ravel` también aplanará un array como `flatten`, pero devuelve una vista del array original cuando sea posible. ```js raveled_array = reshaped_array.ravel() print("Array aplanado con ravel:") print(raveled_array) ```# Aplanar el array con ravel raveled\_array = reshaped\_array.ravel() print("Array aplanado con ravel:") print(raveled\_array)
Para remodelar una matriz 2D de 12 elementos utilizando `reshape`, las nuevas dimensiones deben ser números cuyo producto sea exactamente 12. Esto significa que las dimensiones deben ser divisores de 12. Los divisores de 12 son: 1, 2, 3, 4, 6, 12. Por lo tanto, puedes remodelar la matriz 2D de 12 elementos en cualquiera de las siguientes formas: 1. `(1, 12)` - 1 fila y 12 columnas 2. `(2, 6)` - 2 filas y 6 columnas 3. `(3, 4)` - 3 filas y 4 columnas 4. `(4, 3)` - 4 filas y 3 columnas 5. `(6, 2)` - 6 filas y 2 columnas 6. `(12, 1)` - 12 filas y 1 columna By: ChatGPT
![](https://static.platzi.com/media/user_upload/image-5058ee26-548c-47dc-8d03-5f79a66b4366.jpg)
¿En vertical también se puede imprimir la matrix o solo en horizontal? ![](https://static.platzi.com/media/user_upload/image-19cf9ad5-fb44-45ee-9dc8-e12c7d3dcd0c.jpg)