使用两个1D数组创建numpy的坐标元组

时间:2018-03-12 21:08:58

标签: python arrays numpy

如果我有2个numpy数组:

t.index.get_indexer([(1,1)])[0]
# outputs:
5

如何使用numpy获取以下2D元组数组?

a = [1, 2, 3, 4, 5, 6]
b = [a, b, c, d, e, f]

3 个答案:

答案 0 :(得分:2)

首先:你应该创建一个NxNx2数组,而不是2元组的NxN数组。

如果这样做,您可以使用广播分配来实现所需的阵列:

x = np.arange(6)      # [0, 1, 2, 3, 4, 5]
y = np.arange(6, 12)  # [a, b, c, d, e, f]

out = np.zeros((len(x), len(y), 2))

out[..., 0] = x           # values are repeated for each row
out[..., 1] = y[:, None]  # values are repeated for each column

答案 1 :(得分:0)

Python提供了很多方法来实现这一点。你可以这样做:

[[a0, b0] for a0 in a for b0 in b]

答案 2 :(得分:0)

笛卡尔产品将为您提供所有组合。然后,您可以按第二个键(字母)对该列表进行排序,然后使用列表推导重新嵌套

import numpy as np
import itertools

a = np.array([1, 2, 3, 4, 5, 6])
b = np.array(['a', 'b', 'c', 'd', 'e', 'f'])

out = list(itertools.product(a,b))
out.sort(key=lambda x: x[1])

nested = [out[x:x+len(a)] for x in range(0, len(out), len(a))]

这将给出以下嵌套列表:

[[(1, 'a'), (2, 'a'), (3, 'a'), (4, 'a'), (5, 'a'), (6, 'a')],
 [(1, 'b'), (2, 'b'), (3, 'b'), (4, 'b'), (5, 'b'), (6, 'b')],
 [(1, 'c'), (2, 'c'), (3, 'c'), (4, 'c'), (5, 'c'), (6, 'c')],
 [(1, 'd'), (2, 'd'), (3, 'd'), (4, 'd'), (5, 'd'), (6, 'd')],
 [(1, 'e'), (2, 'e'), (3, 'e'), (4, 'e'), (5, 'e'), (6, 'e')],
 [(1, 'f'), (2, 'f'), (3, 'f'), (4, 'f'), (5, 'f'), (6, 'f')]]

如果您宁愿将其存储为numpy数组而不是创建嵌套列表,那么您很可能希望将其设置为6x6x2而不是2D数组。您可以使用np.array(out).reshape(6,6,2)

执行此操作