How to determine the strategy for changing a numpy array

For a python project, I often find myself modifying and rebuilding numpy n-dimensional arrays. However, it is difficult for me to determine how to approach the problem, visualize the results of the transformation results and find out how effective my solution is.

At the moment when I encountered such a problem, my strategy is to start ipython, download some sample data and go through the trial version and error until I find a combination of transpositions () s, reshape () s and swapaxes () s. which gets the desired result. It does its job, but without a real understanding of what is happening, and often creates code that is difficult to maintain.

So my question is to find a strategy. How do you feel about such a problem? How do you visualize ndarray in your head when you need to format it in the right format? How did you come to the right action?

To answer a slightly more specific example, follow these steps:

Suppose you want to change the next three-dimensional array

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]]])

in a 2d array, where the first columns from the 3rd dimension are placed first, the second - second, .... etc.

The result should look like this:

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

PS. also any reading material on this subject would be great!

+4
source share
1 answer

I regularly play with pieces in ipython. However, to make things clearer, I start with an array with different sizes.

arr = np.arange(3*4*5).reshape(3,4,5)

Thus, it is easier to determine how the axes move, for example:

In [25]: arr.shape
Out[25]: (3, 4, 5)

In [26]: arr.T.shape
Out[26]: (5, 4, 3)

In [31]: arr.T.reshape(5,-1)
Out[31]: 
array([[ 0, 20, 40,  5, 25, 45, 10, 30, 50, 15, 35, 55],
       [ 1, 21, 41,  6, 26, 46, 11, 31, 51, 16, 36, 56],
       [ 2, 22, 42,  7, 27, 47, 12, 32, 52, 17, 37, 57],
       [ 3, 23, 43,  8, 28, 48, 13, 33, 53, 18, 38, 58],
       [ 4, 24, 44,  9, 29, 49, 14, 34, 54, 19, 39, 59]])

( 3,4)

In [38]: np.transpose(arr,[2,0,1]).shape
Out[38]: (5, 3, 4)

In [39]: np.transpose(arr,[2,0,1]).reshape(5,-1)
Out[39]: 
array([[ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55],
       [ 1,  6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56],
       [ 2,  7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57],
       [ 3,  8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58],
       [ 4,  9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59]])

"" , . , - , . , , , . , , , , , .

print arr.shape assert x.shape==y.shape.

:

M, N, L = 3, 4, 5
np.empty((M,N,L))

einsum

np.einsum('ijk,kj->i', A, B) # if A is (M,N,L), B must be (L,N)

fooobar.com/questions/383586/... - rollaxis.

- Python numpy. axis. , . axis . nd 2d, , , . , . , .

, , , (, ) . , "C" .

+3

All Articles