Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Flattening Arrays | Commonly used NumPy Functions
Ultimate NumPy
course content

Contenido del Curso

Ultimate NumPy

Ultimate NumPy

1. NumPy Basics
2. Indexing and Slicing
3. Commonly used NumPy Functions
4. Math with NumPy

bookFlattening Arrays

Sometimes you may need to transform higher-dimensional arrays into simpler 1D arrays. This is where array flattening comes into play.

This operation is useful when you need to process the elements of an array one by one or when you want to make data more suitable for certain algorithms.

There are three possible options for flattening in NumPy:

  • Using the ndarray.reshape(-1) method or the numpy.reshape(array, -1) function;
  • Using the ndarray.ravel() method or the numpy.ravel(array) function;
  • Using the ndarray.flatten() method.

reshape(-1)

The .reshape(-1) method or the reshape(array, -1) function will return a contiguous flattened array with the same number of elements.

As we have already mentioned in the previous chapter, -1 automatically calculates the size of the dimension based on the original array's size. Since we pass only a single integer for shape, a 1D array with the same number of elements is returned.

Here is an example:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.reshape(-1) print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

As you can see, everything is simple here. However, the .reshape() method or the respective function returns a view of the original array, so any changes made to the reshaped array will also affect the original array.

Using flattened_array = np.reshape(array_2d, -1) can be used instead of calling the method.

ravel()

The ndarray.ravel() method or the numpy.ravel(array) function works the same as reshape(-1) and also returns a view of the original array:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.ravel() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

flattened_array = np.ravel(array_2d) can be used instead of calling the method.

ndarray.flatten()

In case you want a copy of the original array, not a view, you can use the .flatten() method:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.flatten() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Initial array:\n{array_2d}')
copy

Now the changes in the flattened array do not affect the original array.

Note

You can always copy a view of an array to create a separate object and modify this copy without affecting the original array.

Tarea
test

Swipe to show code editor

Here's how you can complete the tasks:

  1. Use the .flatten() method correctly for flattening exam_scores and store the result in exam_scores_flattened.

  2. Use the .reshape() method correctly for flattening exam_scores and store the result in exam_scores_reshaped.

  3. Use the .ravel() method for flattening exam_scores and store the result in exam_scores_raveled.

  4. Out of the three created flattened arrays, choose the one that is a copy of the original array, not a view, and assign 100 to its first element (use positive indexing).

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 5
toggle bottom row

bookFlattening Arrays

Sometimes you may need to transform higher-dimensional arrays into simpler 1D arrays. This is where array flattening comes into play.

This operation is useful when you need to process the elements of an array one by one or when you want to make data more suitable for certain algorithms.

There are three possible options for flattening in NumPy:

  • Using the ndarray.reshape(-1) method or the numpy.reshape(array, -1) function;
  • Using the ndarray.ravel() method or the numpy.ravel(array) function;
  • Using the ndarray.flatten() method.

reshape(-1)

The .reshape(-1) method or the reshape(array, -1) function will return a contiguous flattened array with the same number of elements.

As we have already mentioned in the previous chapter, -1 automatically calculates the size of the dimension based on the original array's size. Since we pass only a single integer for shape, a 1D array with the same number of elements is returned.

Here is an example:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.reshape(-1) print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

As you can see, everything is simple here. However, the .reshape() method or the respective function returns a view of the original array, so any changes made to the reshaped array will also affect the original array.

Using flattened_array = np.reshape(array_2d, -1) can be used instead of calling the method.

ravel()

The ndarray.ravel() method or the numpy.ravel(array) function works the same as reshape(-1) and also returns a view of the original array:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.ravel() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

flattened_array = np.ravel(array_2d) can be used instead of calling the method.

ndarray.flatten()

In case you want a copy of the original array, not a view, you can use the .flatten() method:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.flatten() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Initial array:\n{array_2d}')
copy

Now the changes in the flattened array do not affect the original array.

Note

You can always copy a view of an array to create a separate object and modify this copy without affecting the original array.

Tarea
test

Swipe to show code editor

Here's how you can complete the tasks:

  1. Use the .flatten() method correctly for flattening exam_scores and store the result in exam_scores_flattened.

  2. Use the .reshape() method correctly for flattening exam_scores and store the result in exam_scores_reshaped.

  3. Use the .ravel() method for flattening exam_scores and store the result in exam_scores_raveled.

  4. Out of the three created flattened arrays, choose the one that is a copy of the original array, not a view, and assign 100 to its first element (use positive indexing).

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 5
toggle bottom row

bookFlattening Arrays

Sometimes you may need to transform higher-dimensional arrays into simpler 1D arrays. This is where array flattening comes into play.

This operation is useful when you need to process the elements of an array one by one or when you want to make data more suitable for certain algorithms.

There are three possible options for flattening in NumPy:

  • Using the ndarray.reshape(-1) method or the numpy.reshape(array, -1) function;
  • Using the ndarray.ravel() method or the numpy.ravel(array) function;
  • Using the ndarray.flatten() method.

reshape(-1)

The .reshape(-1) method or the reshape(array, -1) function will return a contiguous flattened array with the same number of elements.

As we have already mentioned in the previous chapter, -1 automatically calculates the size of the dimension based on the original array's size. Since we pass only a single integer for shape, a 1D array with the same number of elements is returned.

Here is an example:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.reshape(-1) print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

As you can see, everything is simple here. However, the .reshape() method or the respective function returns a view of the original array, so any changes made to the reshaped array will also affect the original array.

Using flattened_array = np.reshape(array_2d, -1) can be used instead of calling the method.

ravel()

The ndarray.ravel() method or the numpy.ravel(array) function works the same as reshape(-1) and also returns a view of the original array:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.ravel() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

flattened_array = np.ravel(array_2d) can be used instead of calling the method.

ndarray.flatten()

In case you want a copy of the original array, not a view, you can use the .flatten() method:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.flatten() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Initial array:\n{array_2d}')
copy

Now the changes in the flattened array do not affect the original array.

Note

You can always copy a view of an array to create a separate object and modify this copy without affecting the original array.

Tarea
test

Swipe to show code editor

Here's how you can complete the tasks:

  1. Use the .flatten() method correctly for flattening exam_scores and store the result in exam_scores_flattened.

  2. Use the .reshape() method correctly for flattening exam_scores and store the result in exam_scores_reshaped.

  3. Use the .ravel() method for flattening exam_scores and store the result in exam_scores_raveled.

  4. Out of the three created flattened arrays, choose the one that is a copy of the original array, not a view, and assign 100 to its first element (use positive indexing).

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sometimes you may need to transform higher-dimensional arrays into simpler 1D arrays. This is where array flattening comes into play.

This operation is useful when you need to process the elements of an array one by one or when you want to make data more suitable for certain algorithms.

There are three possible options for flattening in NumPy:

  • Using the ndarray.reshape(-1) method or the numpy.reshape(array, -1) function;
  • Using the ndarray.ravel() method or the numpy.ravel(array) function;
  • Using the ndarray.flatten() method.

reshape(-1)

The .reshape(-1) method or the reshape(array, -1) function will return a contiguous flattened array with the same number of elements.

As we have already mentioned in the previous chapter, -1 automatically calculates the size of the dimension based on the original array's size. Since we pass only a single integer for shape, a 1D array with the same number of elements is returned.

Here is an example:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.reshape(-1) print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

As you can see, everything is simple here. However, the .reshape() method or the respective function returns a view of the original array, so any changes made to the reshaped array will also affect the original array.

Using flattened_array = np.reshape(array_2d, -1) can be used instead of calling the method.

ravel()

The ndarray.ravel() method or the numpy.ravel(array) function works the same as reshape(-1) and also returns a view of the original array:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.ravel() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Modified initial array:\n{array_2d}')
copy

flattened_array = np.ravel(array_2d) can be used instead of calling the method.

ndarray.flatten()

In case you want a copy of the original array, not a view, you can use the .flatten() method:

1234567
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]]) flattened_array = array_2d.flatten() print(f'Flatenned array: {flattened_array}') # Changing the first element of flattened_array flattened_array[0] = 10 print(f'Initial array:\n{array_2d}')
copy

Now the changes in the flattened array do not affect the original array.

Note

You can always copy a view of an array to create a separate object and modify this copy without affecting the original array.

Tarea
test

Swipe to show code editor

Here's how you can complete the tasks:

  1. Use the .flatten() method correctly for flattening exam_scores and store the result in exam_scores_flattened.

  2. Use the .reshape() method correctly for flattening exam_scores and store the result in exam_scores_reshaped.

  3. Use the .ravel() method for flattening exam_scores and store the result in exam_scores_raveled.

  4. Out of the three created flattened arrays, choose the one that is a copy of the original array, not a view, and assign 100 to its first element (use positive indexing).

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
Sección 3. Capítulo 5
Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
We're sorry to hear that something went wrong. What happened?
some-alt