[英]2-D numpy array with tuples: expanding into multiple arrays w/combinations of original tuples
Suppose I have a NumPy array like the following: 假设我有一个NumPy数组,如下所示:
0 1 (2,3)
(4,5) 6 7
9 (10,) 11
How could I split it a list of the arrays below? 我如何将其拆分为以下数组的列表? Conditions: no tuples in final arrays, and each array contains a unique combination of the tuple elements.
条件:最终数组中没有元组,并且每个数组都包含元组元素的唯一组合。 That is, there are two tuples in the original array, so there are 4 different combinations of those elements.
也就是说,原始数组中有两个元组,因此这些元素有4种不同的组合。 The first array below has the combination (2) and (4) from the original.
下面的第一个数组具有原始数组的组合(2)和(4)。
0 1 2
4 6 7
9 10 11
0 1 2
5 6 7
9 10 11
0 1 3
4 6 7
9 10 11
0 1 3
5 6 7
9 10 11
Such a data structure is awkward, as @unutbu suggested. 如@unutbu所建议的,这样的数据结构很尴尬。 But if you want to do it, it is doable:
但是,如果您想这样做,那是可行的:
In [52]:
A
Out[52]:
array([[0, 1, (2, 3)],
[(4, 5), 6, 7],
[9, (10,), 11]], dtype=object)
In [53]:
import itertools
AR=A.ravel()
AT=[i for i, val in enumerate(AAR) if isinstance(val, tuple)]
for item in itertools.product(*AR[AT]):
B=AR.copy()
B[AT]=item
print B.reshape(A.shape)
[[0 1 2]
[4 6 7]
[9 10 11]]
[[0 1 2]
[5 6 7]
[9 10 11]]
[[0 1 3]
[4 6 7]
[9 10 11]]
[[0 1 3]
[5 6 7]
[9 10 11]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.