python - numpy.r_ 中的字符串是什么意思?

标签 python numpy

在 numpy 中 documents :

>>> np.r_['0,2,0', [1,2,3], [4,5,6]]
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

字符串“0,2,0”中的第三个数字意味着什么?

最佳答案

我没怎么用过r_的字符串参数;对我来说,直接使用 concatanate 及其变体更容易。

但是查看文档:

A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less than the specified number of dimensions.

'0.2.0'
 axis = 0
 make it 2d
 start with 0d

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

等效的串联

In [80]: np.concatenate(([1,2,3], [4,5,6]))
Out[80]: array([1, 2, 3, 4, 5, 6])
In [81]: np.concatenate(([1,2,3], [4,5,6]))[:,None]
Out[81]: 
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

这里我在 axis=0 上连接,并在连接后扩展到 2d。但听起来 r_ 首先扩展了元素的尺寸(但我们可以仔细检查代码)。

In [83]: alist = ([1,2,3], [4,5,6]) 
In [86]: [np.expand_dims(a,1) for a in alist]
Out[86]: 
[array([[1],
        [2],
        [3]]), array([[4],
        [5],
        [6]])]
In [87]: np.concatenate(_, axis=0)
Out[87]: 
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

我使用 expand_dims 将输入设为 2 d,并在第一个维度之后添加新维度。完成此操作后,我可以在轴 0 上连接。

请注意,r_ 的输入可能已经是二维的,如下所示:

np.r_['0,2,0',[1,2,3], [[4],[5],[6]]]
np.r_['0,2,0',[1,2,3], np.expand_dims([4,5,6],1)]
np.r_['0,2,0',[1,2,3], np.atleast_2d([4,5,6]).T]

3d 数字,如果为 1,则将组件变成

In [105]: np.atleast_2d([4,5,6])
Out[105]: array([[4, 5, 6]])

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

通常,如果文档不清楚,我喜欢深入研究代码,或者尝试其他输入。

In [107]: np.r_['1,2,1',[1,2,3], [4,5,6]]
Out[107]: array([[1, 2, 3, 4, 5, 6]])
In [108]: np.r_['1,2,0',[1,2,3], [4,5,6]]
Out[108]: 
array([[1, 4],
       [2, 5],
       [3, 6]])
<小时/>

查看代码,我发现它使用了

array(newobj, copy=False, subok=True, ndmin=ndmin)

将组件扩展到所需的ndmin。 3d 数字用于构造转置参数。细节比较乱,但是效果大概是这样的:

In [111]: np.array([1,2,3], ndmin=2)
Out[111]: array([[1, 2, 3]])
In [112]: np.array([1,2,3], ndmin=2).transpose(1,0)
Out[112]: 
array([[1],
       [2],
       [3]])

关于python - numpy.r_ 中的字符串是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841269/

相关文章:

python - 使用命令自动加载多个 UNIX screen

python正则表达式从极其复杂的成分字符串中解析数据

python - Numpy高效矩阵自乘(gram矩阵)

python - 如何用代码更改Mayavi中的字体类型和大小?

python - 我的变量在循环内部或外部发生变化

Python模拟补丁实例方法和检查调用参数

python - Django 在bulk_create 中设置自动字段值

python - 列表外积的numpy方式

python - 如何找到具有位置限制的numpy数组的最大值?

python - 如何合并2个数组python(类似于SQL Join)