Understanding the syntax of numpy.r_() concatenation

纵饮孤独 提交于 2019-12-03 01:58:53

'n,m' tells r_ to concatenate along axis=n, and produce a shape with at least m dimensions:

In [28]: np.r_['0,2', [1,2,3], [4,5,6]]
Out[28]: 
array([[1, 2, 3],
       [4, 5, 6]])

So we are concatenating along axis=0, and we would normally therefore expect the result to have shape (6,), but since m=2, we are telling r_ that the shape must be at least 2-dimensional. So instead we get shape (2,3):

In [32]: np.r_['0,2', [1,2,3,], [4,5,6]].shape
Out[32]: (2, 3)

Look at what happens when we increase m:

In [36]: np.r_['0,3', [1,2,3,], [4,5,6]].shape
Out[36]: (2, 1, 3)    # <- 3 dimensions

In [37]: np.r_['0,4', [1,2,3,], [4,5,6]].shape
Out[37]: (2, 1, 1, 3) # <- 4 dimensions

Anything you can do with r_ can also be done with one of the more readable array-building functions such as np.concatenate, np.row_stack, np.column_stack, np.hstack, np.vstack or np.dstack, though it may also require a call to reshape.

Even with the call to reshape, those other functions may even be faster:

In [38]: %timeit np.r_['0,4', [1,2,3,], [4,5,6]]
10000 loops, best of 3: 38 us per loop
In [43]: %timeit np.concatenate(([1,2,3,], [4,5,6])).reshape(2,1,1,3)
100000 loops, best of 3: 10.2 us per loop

The string '0,2' tells numpy to concatenate along axis 0 (the first axis) and to wrap the elements in enough brackets to ensure a two-dimensional array. Consider the following results:

for axis in (0,1):
    for minDim in (1,2,3):
        print np.r_['{},{}'.format(axis, minDim), [1,2,30, 31], [4,5,6, 61], [7,8,90, 91], [10,11, 12, 13]], 'axis={}, minDim={}\n'.format(axis, minDim)

[ 1  2 30 31  4  5  6 61  7  8 90 91 10 11 12 13] axis=0, minDim=1

[[ 1  2 30 31]
 [ 4  5  6 61]
 [ 7  8 90 91]
 [10 11 12 13]] axis=0, minDim=2

[[[ 1  2 30 31]]

 [[ 4  5  6 61]]

 [[ 7  8 90 91]]

 [[10 11 12 13]]] axis=0, minDim=3

[ 1  2 30 31  4  5  6 61  7  8 90 91 10 11 12 13] axis=1, minDim=1

[[ 1  2 30 31  4  5  6 61  7  8 90 91 10 11 12 13]] axis=1, minDim=2

[[[ 1  2 30 31]
  [ 4  5  6 61]
  [ 7  8 90 91]
  [10 11 12 13]]] axis=1, minDim=3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!