It is an exercise from a crash course in numpy
in Python from Google. I've looked at the solution, but I want to know if there's a way to solve my error, and complete the exercise the way I tried at first.
I have tried this:
rand_0_100 = np.random.randint(low=0, high=101, size=(12))
my_data = np.array(
[rand_0_100[0], rand_0_100[1], rand_0_100[2], rand_0_100[3]],
[rand_0_100[4], rand_0_100[5], rand_0_100[6], rand_0_100[7]],
[rand_0_100[8]],
[rand_0_100[9], rand_0_100[10], rand_0_100[11]]
)
... and I get this error:
TypeError: array() takes from 1 to 2 positional arguments but 4 were given
Looking at the solution, I now know I can make the random number from 0-100 an array, by modifying the size
argument to (3, 4)
, but I'd like to know if it is possible to make the array the way I tried.
CodePudding user response:
Yes, that is possible, but you will need to pass a single 2-dimensional list to np.array
, not four 1-dimensional lists:
import numpy as np
rand_0_100 = np.random.randint(low=0, high=101, size=(12))
out = np.array([ # <<< Note this opening [
[rand_0_100[0], rand_0_100[1], rand_0_100[2], rand_0_100[3] ],
[rand_0_100[4], rand_0_100[5], rand_0_100[6], rand_0_100[7] ],
[rand_0_100[8], rand_0_100[9], rand_0_100[10], rand_0_100[11]]
]) # <<< and this closing ]
Numpy also provides a clean way to do this for you using reshape
:
out = rand_0_100.reshape(3, 4)
But as you mention, the best way is to simply pass size=(3, 4)
to randint
.
CodePudding user response:
by the way for the original problem you can have a matrix of 3*4 by this approach :
rand_0_100 =np.random.randint(low=0, high=101, size=(12))
my_data =rand_0_100 .reshape(3,4)
np.array get the arguments as below:
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)
object : is the array you pass to it.
dtype : The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
copy :If true (default), then the object is copied. Otherwise, a copy will only be made if array returns a copy
order: Specify the memory layout of the array.
in your code you gave 4 list as argument to the function. that's why your program face the error
TypeError: array() takes from 1 to 2 positional arguments but 4 were given
hope it helps.