使用序列创建Numpy数组

时间:2017-12-08 20:09:01

标签: python arrays numpy

我见过this,但它并没有完全回答我的问题。

我有一个数组:

x = np.array([0, 1, 2])

我想要这个:

y = np.array([[0,1], [0,2], [1,0], [1,2], [2,0], [2,1]])

也就是说,我想获取数组i的每个值(我们称之为x)并使用{{1}的所有其他值创建x.shape[0]-1个新数组},不包括x

基本上i包含没有任何对角元素的3x3矩阵的索引。

我觉得有一种简单,pythonic的做法就是不会来找我。

2 个答案:

答案 0 :(得分:1)

方法#1:一种方法是 -

x[np.argwhere(~np.eye(len(x),dtype=bool))]

方法#2:分两个步骤 -

r = np.arange(len(x))
out = x[np.argwhere(r[:,None]!=r)]

方法#3:为了提高性能,最好先创建成对坐标,然后再进行遮罩。要获得paiwise坐标,让我们使用cartesian_product_transpose,就像这样 -

r = np.arange(len(x))
mask = r[:,None]!=r
out = cartesian_product_transpose(x,x)[mask.ravel()]

方法#4: np.broadcast_to的另一个方法可以避免在屏蔽之前制作副本,这再次意味着作为一项效果指标 -

n = len(x)
r = np.arange(n)
mask = r[:,None]!=r
c0 = np.broadcast_to(x[:,None], (n, n))[mask]
c1 = np.broadcast_to(x, (n,n))[mask]
out = np.column_stack((c0,c1))

运行时测试 -

In [382]: x = np.random.randint(0,9,(1000))

# @tom10's soln
In [392]: %timeit list(itertools.permutations(x, 2))
10 loops, best of 3: 62 ms per loop

In [383]: %%timeit
     ...: x[np.argwhere(~np.eye(len(x),dtype=bool))]
100 loops, best of 3: 11.4 ms per loop

In [384]: %%timeit
     ...: r = np.arange(len(x))
     ...: out = x[np.argwhere(r[:,None]!=r)]
100 loops, best of 3: 12.9 ms per loop

In [388]: %%timeit
     ...: r = np.arange(len(x))
     ...: mask = r[:,None]!=r
     ...: out = cartesian_product_transpose(x,x)[mask.ravel()]
100 loops, best of 3: 16.5 ms per loop

In [389]: %%timeit
     ...: n = len(x)
     ...: r = np.arange(n)
     ...: mask = r[:,None]!=r
     ...: c0 = np.broadcast_to(x[:,None], (n, n))[mask]
     ...: c1 = np.broadcast_to(x, (n,n))[mask]
     ...: out = np.column_stack((c0,c1))
100 loops, best of 3: 6.72 ms per loop

答案 1 :(得分:0)

除非你真的需要速度等,否则纯粹的Python提供了一个更清晰的解决方案:

import itertools

y = itertools.permutations([0, 1, 2], 2)

# [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]