Sun Hao Lun
Sun Hao Lun

Reputation: 313

Python Initialize multidimensional numpy array of random value

If I want to bulid a 3-dimensional array And I can write something like this (x is the 3-dimensional array)

for i in range(pN): 
    for j in range(C): 
        for k in range(K+1):
            X[i][j][k] = random.uniform(0,1) #random initialize

But how can I make this code to be more readable? (For example, don't use 3 for loop)

Thanks!

Upvotes: 2

Views: 1162

Answers (4)

Raymond Mutyaba
Raymond Mutyaba

Reputation: 950

import numpy as np

X = np.random.uniform(0, 1, (x, y, z))
# x, y, z would represent the size of each dimension

From the numpy documentation

Upvotes: 1

wasif
wasif

Reputation: 15470

Use numpy instead.

First install it with

pip install -U numpy

In terminal or windows command prompt.

Then in python program import it with:

import numpy as np

And then use random.rand:

np.random.rand((pN,C,K))

Upvotes: 1

isaaccs
isaaccs

Reputation: 103

you can use numpy

import numpy as np
np.random.random((pN,C,K))

Upvotes: 1

Maksim Khaitovich
Maksim Khaitovich

Reputation: 4792

Just use numpy random function:

https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.rand.html

It will generate random array of a shape you want (like 3x2x3)

 np.random.rand(3,2,3)

Upvotes: 2

Related Questions