[PYTHON] Small story: numpy flatten mechanism

I often flatten the ndarray of numpy, but let's understand the order in which the data are arranged.

Create ndarray of (3, 3, 3). The values are given serial numbers so that you can see which value is assigned to which position.

import numpy as np

x = np.array([[[ 0,  1,  2], [ 3,  4,  5], [ 6,  7,  8]], 
              [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], 
              [[18, 19, 20], [21, 22, 23], [24, 25, 26]],])
print(x.shape)

out


(3, 3, 3)

If you np.flatten () this, let's see how it is arranged in one dimension.

x.flatten()

It turns out that the deepest nests are taken in order and arranged in one dimension! It's relatively intuitive.

out


array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26])

It ’s short, but that ’s it!

Recommended Posts

Small story: numpy flatten mechanism
[Memo] Small story of pandas, numpy
python small story collection
App Service Small story collection
[Small story] Get timestamp with Python