Flattening
Do you know what it means to flatten an array? Flattening is the process of transforming a multidimensional array into a one-dimensional one.
This transformation can be achieved using two different methods:
- the first one we're already familiar with is the
.reshape(-1)
method with an argument of-1
; - the other option is to use the
.flatten()
method.
Now, let's have a look at both of these methods in practice.
Let's see how to use the .reshape(-1)
method:
123456import numpy as np array = np.array([[12, 45, 78, 34, 0], [13, 5, 78, 3, 1]]) new_array = array.reshape(-1) print(new_array)
Let's see how to use the .flatten()
method:
123456import numpy as np array = np.array([[12, 45, 78, 34, 0], [13, 5, 78, 3, 1]]) new_array = array.flatten() print(new_array)
Let's practice!
Swipe to start coding
Consider the following array:
[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]]
You should transform it into the following array:
[1 2 3 4 5 6 7 8 9 10 11 12]
.
Lösning
Tack för dina kommentarer!
single
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 4.76
Flattening
Svep för att visa menyn
Do you know what it means to flatten an array? Flattening is the process of transforming a multidimensional array into a one-dimensional one.
This transformation can be achieved using two different methods:
- the first one we're already familiar with is the
.reshape(-1)
method with an argument of-1
; - the other option is to use the
.flatten()
method.
Now, let's have a look at both of these methods in practice.
Let's see how to use the .reshape(-1)
method:
123456import numpy as np array = np.array([[12, 45, 78, 34, 0], [13, 5, 78, 3, 1]]) new_array = array.reshape(-1) print(new_array)
Let's see how to use the .flatten()
method:
123456import numpy as np array = np.array([[12, 45, 78, 34, 0], [13, 5, 78, 3, 1]]) new_array = array.flatten() print(new_array)
Let's practice!
Swipe to start coding
Consider the following array:
[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]]
You should transform it into the following array:
[1 2 3 4 5 6 7 8 9 10 11 12]
.
Lösning
Tack för dina kommentarer!
Awesome!
Completion rate improved to 4.76single