繁体   English   中英

如何在numpy中连接使用自定义dtype的n个数组的项目

[英]How to concatenate items of n arrays which use custom dtype in numpy

我有一个自定义 dtype 定义为:

myType = np.dtype([
    ('foo', 'u4'),
    ('bar', 'f8')
])

我定义了这个自定义 dtype 的 n 个向量(在这个例子中只有两个):

a=np.array([(2, 1.1), (3, 2.2)], dtype=myType)
b=np.array([(4, 3.3), (5, 4.4), (6, 5.5)], dtype=myType)
print(np.shape(a))
print(np.shape(b))

我将 n 个向量分组在一个 python 列表中:

data = [a,b]   # Will be n vectors, not just two

我想加入两个向量,所以我会得到一个向量 c,就像我做的一样:

c=np.array([(2, 1.1), (3, 2.2), (4, 3.3), (5, 4.4), (6, 5.5)], dtype=myType)
print(np.shape(c))
c

我尝试:

np.vstack(data)

但我收到以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-67-f65a6d8e700e> in <module>
----> 1 np.vstack(data)

<__array_function__ internals> in vstack(*args, **kwargs)

~/.local/lib/python3.6/site-packages/numpy/core/shape_base.py in vstack(tup)
    281     if not isinstance(arrs, list):
    282         arrs = [arrs]
--> 283     return _nx.concatenate(arrs, 0)
    284 
    285 

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 3

使用np.concatenate

import numpy as np

myType = np.dtype([
    ('foo', 'u4'),
    ('bar', 'f8')
])

a = np.array([(2, 1.1), (3, 2.2)], dtype=myType)
b = np.array([(4, 3.3), (5, 4.4), (6, 5.5)], dtype=myType)

result = np.concatenate((a, b))
print(result)

输出

[(2, 1.1) (3, 2.2) (4, 3.3) (5, 4.4) (6, 5.5)]

np.hstack

result = np.hstack((a, b))
In [49]: a=np.array([(2, 1.1), (3, 2.2)], dtype=myType)
    ...: b=np.array([(4, 3.3), (5, 4.4), (6, 5.5)], dtype=myType)
In [50]: a
Out[50]: array([(2, 1.1), (3, 2.2)], dtype=[('foo', '<u4'), ('bar', '<f8')])
In [51]: a.shape
Out[51]: (2,)
In [52]: b.shape
Out[52]: (3,)

a,b是 1d,因此在(默认)轴 0 上串联工作:

In [53]: np.concatenate((a,b))
Out[53]: 
array([(2, 1.1), (3, 2.2), (4, 3.3), (5, 4.4), (6, 5.5)],
      dtype=[('foo', '<u4'), ('bar', '<f8')])

vstack生成 (1,2) 和 (1,3) 并尝试连接大小为 1,从而导致错误。 它对问题的维度非常明确。

特殊的dtype不是问题 - 除了您将数组视为 2d。

暂无
暂无

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

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