在python中填充数组

时间:2019-02-23 07:04:00

标签: python arrays numpy

我想用一些数字填充数组,输出应该像这样:

[[x1, y1, z1],
 [x1, y2, z2],
 [x2, y1, z3],
 [x2, y2, z4],
 [x3, y1, z5],
 [x3, y2, z6]]

我有数据x,y和z(列表),数据内部有3个x值,2个y值和6个z值。

我尝试创建一个新数组,然后使用for或while循环填充它,但无法完全填充它。

如何在numpy中使用python而不手动填充它?

2 个答案:

答案 0 :(得分:2)

对于纯Python解决方案,可以使用任何列表大小。

x = [11,12,13,14,15]
y = [21,23,24]
z = [31,32,33,34,35,36,37]

详细代码:

tmp = []
for i in range(max(len(x), len(y), len(z))):
    for yy in y:
        tmp.append([x[i%len(x)], yy])

for i in range(len(tmp)):
    tmp[i].append((z[i%len(z)]))

返回

# [[11, 21, 31],
#  [11, 23, 32],
#  [11, 24, 33],
#  [12, 21, 34],
#  [12, 23, 35],
#  [12, 24, 36],
#  [13, 21, 37],
#  [13, 23, 31],
#  [13, 24, 32],
#  [14, 21, 33],
#  [14, 23, 34],
#  [14, 24, 35],
#  [15, 21, 36],
#  [15, 23, 37],
#  [15, 24, 31],
#  [11, 21, 32],
#  [11, 23, 33],
#  [11, 24, 34],
#  [12, 21, 35],
#  [12, 23, 36],
#  [12, 24, 37]]

答案 1 :(得分:1)

分别在x和y上使用np.repeatnp.tile获得所需的列,然后将它们与z一起堆叠到一个数组中:

import numpy as np

x = [1, 2, 3]
y = [4, 5]
z = [6, 7, 8, 9, 10, 11]

a = np.array([np.repeat(x, 2), np.tile(y, 3), z]).T

结果:

array([[ 1,  4,  6],
       [ 1,  5,  7],
       [ 2,  4,  8],
       [ 2,  5,  9],
       [ 3,  4, 10],
       [ 3,  5, 11]])