在多维numpy数组中均匀分配索引

时间:2018-08-06 10:02:43

标签: python arrays python-2.7 numpy

我想在python中创建一个代码段,以在具有重复值的多维数组上均匀地分配一系列索引,这样我就可以为尺寸为(7,13)的数组获取此信息:

[[0 0 0 1 1 1 2 2 2 3 3 3 1]
 [0 0 0 1 1 1 2 2 2 3 3 3 2]
 [0 0 0 1 1 1 2 2 2 3 3 3 0]
 [0 0 0 1 1 1 2 2 2 3 3 3 1]
 [0 0 0 1 1 1 2 2 2 3 3 3 3]
 [0 0 0 1 1 1 2 2 2 3 3 3 1]
 [0 0 0 1 1 1 2 2 2 3 3 3 2]]

对于等号f.ex的数组,这是微不足道的。 N = 12、16。但是对于其他情况,我想在该行中复制一个随机数。

此外,应该对其进行概括,以便每行可以具有变化的最大数。第4行的最大值可能为5,这样

[[0 0 0 1 1 1 2 2 2 3 3 3 1]
 [0 0 0 1 1 1 2 2 2 3 3 3 2]
 [0 0 0 1 1 1 2 2 2 3 3 3 0]
 [0 0 1 1 2 2 3 3 4 4 5 5 5]
 [0 0 0 1 1 1 2 2 2 3 3 3 3]
 [0 0 0 1 1 1 2 2 2 3 3 3 1]
 [0 0 0 1 1 1 2 2 2 3 3 3 2]]

到目前为止,我已经尝试过这样做

matches=[]
for pos in range(num_pos):
    matches.append([i for i in range(0, lens[pos]) for _ in range(num_opp/lens[pos])])

matches = np.asarray(matches) # Matrix of perfect matches

,其中不包括num_opp / lens [pos]的多余部分,这些部分加起来就成为每行中的另一个元素。

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

def make_index_matrix(dim, max_values):
    assert len(max_values) == dim[0]
    out = np.zeros(dim)

    for k, mv in enumerate(max_values):
        assert mv > 0
        a = np.arange(mv).repeat(np.floor(dim[1]/mv))

        if len(a) < dim[1]:
            r = np.arange(mv)
            np.random.shuffle(r)
            a = np.concatenate((a, r))

        out[k,:] = a[:dim[1]]

    return out

第一个参数定义矩阵尺寸,第二个参数应每行包含一个值(> 0),以给出上限。

一些例子:

In [3]: make_index_matrix((4, 4), np.arange(1, 5))
Out[3]: 
array([[0., 0., 0., 0.],
       [0., 0., 1., 1.],
       [0., 1., 2., 1.],
       [0., 1., 2., 3.]])
In [4]: make_index_matrix((4, 11), np.arange(1, 5))
Out[4]: 
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1.],
       [0., 0., 0., 1., 1., 1., 2., 2., 2., 2., 1.],
       [0., 0., 1., 1., 2., 2., 3., 3., 3., 2., 0.]]