简体   繁体   English

组合两个不同维度的numpy数组

[英]Combinig two numpy arrays of different dimensions

I want to add one numpy array two another so it will look like this:我想添加一个numpy数组,另外两个,所以它看起来像这样:

a = [3, 4]
b = [[6, 5], [2, 1]]

output:输出:

[[3, 4], [[6, 5], [2, 1]]]

It should look like the output above and not like [[3,4],[6,5],[2,1]] .它应该看起来像上面的输出,而不是像[[3,4],[6,5],[2,1]]

How do I do that with numpy arrays?我如何使用numpy数组来做到这一点?

Work with pure python list s, and not numpy arrays.使用纯 python list s,而不是numpy数组。

It doesn't make sense to have a numpy array holding two list objects.拥有一个包含两个list对象的numpy数组是没有意义的。 There's literally no gain in doing that.这样做实际上没有任何好处。


If you directly instantiate an array like so:如果你像这样直接实例化一个数组:

np.array([[3, 4], [[6, 5], [2, 1]]])

You get你得到

array([[3, 4],
       [list([6, 5]), list([2, 1])]], dtype=object)

which is an array with dtype= object .这是一个 dtype= object的数组。 Most of numpy's power is lost in this case.在这种情况下,numpy 的大部分功能都会丢失。 For more information on examples and why, take a look at this thread .有关示例及其原因的更多信息,请查看此线程


If you work with pure python lists, then you can easily achieve what you want:如果您使用纯 python 列表,那么您可以轻松实现您想要的:

>>> a + b
[[3, 4], [[6, 5], [2, 1]]]

Numpy as built-in stack commands that are (in my opinion) slightly easier to use: Numpy 作为内置堆栈命令(在我看来)更容易使用:

>>> a = np.array([3, 4])
>>> b = np.array([[6, 5], [2, 1]])
>>> np.row_stack([b, a])
array([[3, 4],
       [6, 5],
       [2, 1]])

There's also a column stack.还有一个列堆栈。 Ref: https://numpy.org/doc/stable/reference/generated/numpy.ma.row_stack.html参考: https ://numpy.org/doc/stable/reference/generated/numpy.ma.row_stack.html

You can't stack arrays of different shapes in one array the way you want (or you have to fill in gaps with NaNs or zeroes), so if you want to iterate over them, consider using list.您不能以您想要的方式将不同形状的数组堆叠在一个数组中(或者您必须用 NaN 或零填充空白),因此如果您想遍历它们,请考虑使用 list.

a = np.array([3, 4])
b = np.array([[6, 5], [2, 1]])
c = [a, b]
for arr in c:
    ...

If you still want a numpy array, you can try this:如果你仍然想要一个 numpy 数组,你可以试试这个:

>>> a = np.array([3, 4])
>>> b = np.array([[6, 5], [2, 1]])
>>> a.resize(b.shape,refcheck=False)
>>> c = np.array([a, b])

array([[[3, 4],
        [0, 0]],

       [[6, 5],
        [2, 1]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM