Ridimensionare gli arrays
Another useful type of operation is reshaping of arrays. The most flexible way of doing this is with the
reshape method. For example, if you want to put the numbers 1 through 9 in a 3×3 grid, you can do the following:
Note that for this to work, the size of the initial array must match the size of the reshaped array. Where possible, the
reshape method will use a no-copy view of the initial array, but with non-contiguous memory buffers this is not always the case.
Another common reshaping pattern is the conversion of a one-dimensional array into a two-dimensional row or column matrix. This can be done with the
reshape method, or more easily done by making use of the
newaxis keyword within a slice operation:
We will see this type of transformation often throughout the remainder of the book. Da ricordarselo; io sarei per l’altra versione.
Concatenazione e suddivisione di arrays
All of the preceding routines worked on single arrays. It’s also possible to combine multiple arrays into one, and to conversely split a single array into multiple arrays. We’ll take a look at those operations here.
Concatenazione di arrays
Concatenation, or joining of two arrays in NumPy, is primarily accomplished using the routines
np.concatenate takes a tuple or list of arrays as its first argument, as we can see here:
You can also concatenate more than two arrays at once:
It can also be used for two-dimensional arrays:
For working with arrays of mixed dimensions, it can be clearer to use the
np.vstack (vertical stack) and
np.hstack (horizontal stack) functions:
np.dstack will stack arrays along the third axis.
The opposite of concatenation is splitting, which is implemented by the functions
np.vsplit. For each of these, we can pass a list of indices giving the split points:
N split-points, leads to
N + 1 subarrays. The related functions
np.vsplit are similar:
np.dsplit will split arrays along the third axis.