3

How can I fill the numpy array by rows?

For example arr=np.zeros([3,2]). I want replace every row by list = [1,2].

So output is:

[1 2 
 1 2
 1 2]

I can make it by hand

for x in arr[:]:
    arr[:]=[1,2]

But I believe there is more faster ways.

Sorry, please look edit: Suppose, we have:

arr=array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

I want arr[1] array fill by [1,2] like this:

arr=array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  1.,  1.],
        [ 2.,  2.,  2.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])
2
  • Is your original array actually all zeroes? Commented Nov 28, 2016 at 6:22
  • Whst is your array's shapw? Commented Nov 28, 2016 at 6:26

2 Answers 2

4

Your loop isn't necessary.

Making use of broadcasting, you can do this with a single assignment:

arr[:] = [1,2]

Numpy broadcasts the right-hand-side array to a shape assignable to the left-hand-side.


As for the second question (in your update), you can do:

arr.T[..., 1] = [1,2]
Sign up to request clarification or add additional context in comments.

Comments

1

In this case, simple assignment to the whole array works:

In [952]: arr=np.zeros((3,2),int)
In [953]: arr[...]=[1,2]
In [954]: arr
Out[954]: 
array([[1, 2],
       [1, 2],
       [1, 2]])

That's because the list translates into a (2,) array, which can be broadcasted to (1,2) and then (3,2), to match arr:

In [955]: arr[...]=np.array([3,2])[None,:]
In [956]: arr
Out[956]: 
array([[3, 2],
       [3, 2],
       [3, 2]])

If I want to set values by column, I have to do a bit more work

In [957]: arr[...]=np.array([1,2,3])[:,None]
In [958]: arr
Out[958]: 
array([[1, 1],
       [2, 2],
       [3, 3]])

I have to explicitly make a (3,1) array, which broadcasts to (3,2).

=================

I already answered your modified question:

In [963]: arr[1,...]=np.array([1,2])[:,None]
In [964]: arr
Out[964]: 
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  1.,  1.],
        [ 2.,  2.,  2.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

=================

Add tile to your toolkit:

In [967]: np.tile([1,2],(3,1))
Out[967]: 
array([[1, 2],
       [1, 2],
       [1, 2]])
In [968]: np.tile([[1],[2]],(1,3))
Out[968]: 
array([[1, 1, 1],
       [2, 2, 2]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.