Data mining numpy advanced skills and tips

"Automatically" change shape

To change the dimensions of the array, you can omit a dimension and it will be deduced automatically.

>>> a = arange(30)
>>> a.shape = 2,-1,3  # -1 means "whatever is needed"
>>> a.shape
(2, 5, 3)
>>> a
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],
        [27, 28, 29]]])

vector stacking

How do we build a 2D array from two lists of row vectors of the same size?

In NumPy this is done with the functions column_stack, dstack, hstackand vstack, depending on which dimension you want to compose in. E.g:

x = arange(0,10,2)                     # x=([0,2,4,6,8])
y = arange(5)                          # y=([0,1,2,3,4])
m = vstack([x,y])                      # m=([[0,2,4,6,8],
                                       #     [0,1,2,3,4]])
xy = hstack([x,y])                     # xy =([0,2,4,6,8,0,1,2,3,4])
mm = numpy.dstack(x)                   # mm =([[[0 2 4 6 8]]])

The logic behind these functions in two dimensions would be weird.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249794&siteId=291194637