[英]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.