gpt4 book ai didi

python - 了解 numpy.r_() 串联的语法

转载 作者:太空狗 更新时间:2023-10-29 17:06:21 24 4
gpt4 key购买 nike

我在函数 r_ 的 numpy 文档中阅读了以下内容:

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 做什么?

除了上面的链接,是否还有其他站点提供有关此功能的更多文档?

最佳答案

'n,m' 告诉 r_ 沿 axis=n 连接,并生成至少具有 m< 的形状尺寸:

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

所以我们沿着 axis=0 连接,因此我们通常希望结果具有 (6,) 的形状,但是由于 m=2,我们是告诉 r_ 形状必须至少是二维的。所以我们得到形状 (2,3):

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

看看当我们增加 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.concatenatenp.row_stacknp.column_stacknp.hstacknp.vstacknp.dstack,虽然它可能还需要调用 reshape

即使调用 reshape,那些其他函数甚至可能更快:

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

关于python - 了解 numpy.r_() 串联的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14468158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com