7

I'm new to python/numpy and I need to create an array containing matrices of random numbers.

What I've got so far is this:

for i in xrange(samples):
    SPN[] = np.random.random((6,5)) * np.random.randint(0,100)

Which make sense for me as PHP developer but is not working for python. So how do I create a 3 dimensional array to contain this matrices/arrays?

4

1 回答 1

18

np.random.randint和 和np.random.uniform大多数函数一样,都np.random接受一个size参数,所以numpy我们一步一步完成:

>>> SPN = np.random.randint(0, 100, (3, 6, 5))
>>> SPN
array([[[45, 95, 56, 78, 90],
        [87, 68, 24, 62, 12],
        [11, 26, 75, 57, 12],
        [95, 87, 47, 69, 90],
        [58, 24, 49, 62, 85],
        [38,  5, 57, 63, 16]],

       [[61, 67, 73, 23, 34],
        [41,  3, 69, 79, 48],
        [22, 40, 22, 18, 41],
        [86, 23, 58, 38, 69],
        [98, 60, 70, 71,  3],
        [44,  8, 33, 86, 66]],

       [[62, 45, 56, 80, 22],
        [27, 95, 55, 87, 22],
        [42, 17, 48, 96, 65],
        [36, 64,  1, 85, 31],
        [10, 13, 15,  7, 92],
        [27, 74, 31, 91, 60]]])
>>> SPN.shape
(3, 6, 5)
>>> SPN[0].shape
(6, 5)

.. 实际上,看起来您可能想要np.random.uniform(0, 100, (samples, 6, 5)),因为您希望元素是浮点数,而不是整数。好吧,它的工作方式相同。:^)


请注意,您所做的并不等同于np.random.uniform,因为您选择了一个介于 0 和 1 之间的值数组,然后将所有这些值乘以一个固定整数。我假设这实际上不是您想要做的,因为这有点不寻常;如果那您真正想要的,请发表评论。

于 2013-11-14T17:46:42.527 回答