[英]Zip uneven numpy arrays
考慮以下numpy.arrays
:
a = np.array([1., 2., 3.])
b = np.array([4., 5.])
c = np.array([6., 7.])
我需要結合這些,所以我最終得到以下內容:
[(1., 4., 6.), (1., 5., 7.), (2., 4., 6.), (2., 5., 7.), (3., 4., 6.), (3., 5., 7.)]
請注意,在這種情況下,數組a
恰好是最大的數組。 但是,這並不能保證。 長度也不保證。 換句話說,任何數組都可以是最長的,每個數組都是任意長度的。
我嘗試使用itertools.izip_longest
但我只能使用fillvalue
作為3的元組3.
這將無效。 我也試過了itertools.product
但我的結果並不是真正的笛卡爾積。
可以移調b
和c
,然后創建一個產品a
使用轉置數組itertools.product
:
>>> from itertools import product
>>> [np.insert(j,0,i) for i,j in product(a,np.array((b,c)).T)]
[array([ 1., 4., 6.]), array([ 1., 5., 7.]), array([ 2., 4., 6.]), array([ 2., 5., 7.]), array([ 3., 4., 6.]), array([ 3., 5., 7.])]
>>>
假設你有:
a = np.array([4., 5.])
b = np.array([1., 2., 3.])
c = np.array([6., 7.])
d = np.array([5., 1])
e = np.array([3., 2.])
現在,如果你事先知道哪一個是最長的數組,在這種情況下是b
,你可以使用基於np.meshgrid
的方法 -
# Concatenate elements from identical positions from the equal arrays
others = np.vstack((a,c,d,e)).T # If you have more arrays, edit this line
# Get grided version of the longest array and
# grided-indices for indexing into others array
X,Y = np.meshgrid(np.arange(others.shape[0]),b)
# Concatenate grided longest array and grided indexed others for final output
out = np.hstack((Y.ravel()[:,None],others[X.ravel()]))
樣品運行 -
In [47]: b
Out[47]: array([ 1., 2., 3.])
In [48]: a
Out[48]: array([ 4., 5.])
In [49]: c
Out[49]: array([ 6., 7.])
In [50]: d
Out[50]: array([ 5., 1.])
In [51]: e
Out[51]: array([ 3., 2.])
In [52]: out
Out[52]:
array([[ 1., 4., 6., 5., 3.],
[ 1., 5., 7., 1., 2.],
[ 2., 4., 6., 5., 3.],
[ 2., 5., 7., 1., 2.],
[ 3., 4., 6., 5., 3.],
[ 3., 5., 7., 1., 2.]])
如果長度差異不是極端的(首先檢查輸入),我很想將較短的列表填充到最長的無限長度並生成所有排列(其中27個為3個元素的3個列表)。 然后
results = []
for candidate in possibles:
if not (None in candidate): results.append(candidate)
不這樣做的原因:如果最長列表的長度的多維數據集在內存使用(存儲N個可能的空間的空間)或CPU使用方面是重要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.