【问题标题】:Distribute indices evenly in multidimensional numpy array在多维 numpy 数组中均匀分布索引
【发布时间】:2018-08-06 10:02:43
【问题描述】:

我想在 python 中创建一个 sn-p 以在具有重复值的多维数组上均匀分布一系列索引,这样我就可以得到一个维度为 (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]) 的额外分数,它们加起来是每一行中的另一个元素。

【问题讨论】:

  • 请贴出你尝试过的代码

标签: python arrays python-2.7 numpy


【解决方案1】:

这应该可以解决问题:

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.]]

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多