Home > OS >  How do I can get array like this array([[0.37454012], [0.95071431], [0.73199394]]) using Numpy
How do I can get array like this array([[0.37454012], [0.95071431], [0.73199394]]) using Numpy

Time:03-23

I have a function that takes 2 parameters and returns a shape of an array. where the function that will create a Numpy array of a given shape with random values. The output should be like this: array([[0.37454012], [0.95071431], [0.73199394]]), but I got it like this: arrayarray([[0.37454012, 0.95071431, 0.73199394]])).

What is the methoud that I can use to return it like this: ([[0.37454012], [0.95071431], [0.73199394]])

For example, initialise_array(3,1) will return an array of dimensions (3,1) that can look like this:

array([[0.37454012], [0.95071431], [0.73199394]])

My code:

def initialise_array(n_features, n_observations): 
    shape = np.random.rand(n_features, n_observations) 
    n_shape = shape.reshape(n_observations, n_features) 
    return n_shape

The output looks like array([[0.85546058, 0.70365786, 0.47417383]]) but I need to match the this array([[0.37454012], [0.95071431], [0.73199394]])

CodePudding user response:

If I understand correctly, just get rid of your reshape call

def initialise_array(n_features, n_observations): 
    shape = np.random.rand(n_features, n_observations) 
    return shape

Output:

>>> initialise_array(3, 1)
array([[0.38454951],
       [0.61060765],
       [0.84899489]])

CodePudding user response:

The first thing to note is that parameters passed to np.random.rand define just the shape of the array to be created.

So much shorter and simpler code than yours is:

def initialise_array(n_features, n_observations): 
    return np.random.rand(n_features, n_observations)

When you call this function as: initialise_array(3, 1) you will get an array with 3 rows and a single column. Just as you wish.

And a remark about your code:

It is misleading in the way you use variable names.

Note that what you save under shape variable is not any shape, but an array (of the shape passed with parameters).

  • Related