Reputation: 596
I want to generate a an array of ordered numbers and then multiply it into another array :
[ [0,1,2,3,4,5] [0,1,2,3,4,5] [0,1,2,3,4,5] ... [0,1,2,3,4,5] ]
I can generate the first [0,1,2,3,4,5] with nums = np.arange(0, 6)
but then if I multiply by a number inside a list it just increases the values = [nums* 3] = [0,3,6,9,12,15]
.
How can I do this ?
Upvotes: 2
Views: 2685
Reputation: 61325
BTW, why not simply use np.array()
as in:
In [147]: nums = np.arange(6)
In [148]: nums
Out[148]: array([0, 1, 2, 3, 4, 5])
In [149]: [nums] * 5
Out[149]:
[array([0, 1, 2, 3, 4, 5]),
array([0, 1, 2, 3, 4, 5]),
array([0, 1, 2, 3, 4, 5]),
array([0, 1, 2, 3, 4, 5]),
array([0, 1, 2, 3, 4, 5])]
In [150]: np.array([nums] * 5)
Out[150]:
array([[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]])
In one-line:
In [151]: np.array([np.arange(6)] * 5)
Out[151]:
array([[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]])
Upvotes: 3
Reputation: 28233
you can't multiply a numpy array with a scalar and expect the same behaviour as multiplying a python list (or string) with a scalar.
for numpy, the multiplication operator will broadcast the multiplication over all the array elements:
i.e.
np.array([1,2,3]) * 2 == np.array([1*2, 2*2, 3*2) == np.array([2,4,6])
instead, you can use a list comprehension
np.array([np.arange(6) for _ in range(4)])
array([[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]])
or generate a list of lists through multiplication and then convert to numpy array & reshape:
np.array([list(range(6))*4]).reshape(4,6)
array([[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]])
or, generate an array of shape (1,6) and repeat along the first axix:
np.repeat(np.arange(6).reshape(1,6), repeats=4, axis=0)
# produces the same output as the example outputs above.
Upvotes: 1
Reputation: 51335
Using numpy
methods (numpy.repeat
and numpy.expand_dims
):
np.repeat(np.expand_dims(np.arange(0,6), axis=0), repeats=5, axis=0)
array([[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]])
Or, more simply:
np.repeat([np.arange(0,6)],repeats=5, axis=0)
The first method is useful if you were trying to expand a pre-existing one dimensional array. If you are trying to create your array from the start, the second method is more straightforward.
Upvotes: 7