了解numpy.r_()串联的语法 [英] Understanding the syntax of numpy.r_() concatenation
问题描述
我在numpy文档中阅读了有关功能 r_ 的以下内容:
I read the following in the numpy documentation for the function r_:
一个字符串整数指定要堆叠多个逗号的轴 分开的数组.由两个逗号分隔的整数组成的字符串 允许指示最小尺寸以强制每个尺寸 进入作为第二个整数(要串联的轴是 仍然是第一个整数).
A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-separated integers allows indication of the minimum number of dimensions to force each entry into as the second integer (the axis to concatenate along is still the first integer).
他们给出了这个例子:
>>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2
array([[1, 2, 3],
[4, 5, 6]])
我不遵循,字符串'0,2'
到底指示numpy做什么?
I don't follow, what does exactly the string '0,2'
instruct numpy to do?
除了上面的链接之外,还有其他网站提供有关此功能的更多文档吗?
Other than the link above, is there another site with more documentation about this function?
推荐答案
'n,m'
告诉r_
沿axis=n
并置,并产生至少具有m
尺寸的形状:
'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]])
因此,我们沿着轴= 0进行连接,因此通常期望结果具有形状(6,)
,但是由于m=2
,我们告诉r_
形状必须至少为二维.因此,我们得到形状(2,3)
:
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)
看看当我们增加m
时会发生什么:
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
使用r_
可以执行的任何操作也可以使用更具可读性的数组构建功能之一来完成,例如np.concatenate
,np.row_stack
,np.column_stack
,np.hstack
,np.vstack
或np.dstack
,尽管它可能还需要调用reshape
.
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
这篇关于了解numpy.r_()串联的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!