29

I have an array like this

import numpy as np

a = np.zeros((2,2), dtype=np.int)

I want to replace the first column by the value 1. I did the following:

a[:][0] = [1, 1] # not working
a[:][0] = [[1], [1]] # not working

Contrariwise, when I replace the rows it worked!

a[0][:] = [1, 1] # working

I have a big array, so I cannot replace value by value.

0

3 Answers 3

58

You can replace the first column as follows:

>>> a = np.zeros((2,2), dtype=np.int)
>>> a[:, 0] =  1
>>> a
array([[1, 0],
       [1, 0]])

Here a[:, 0] means "select all rows from column 0". The value 1 is broadcast across this selected column, producing the desired array (it's not necessary to use a list [1, 1], although you can).

Your syntax a[:][0] means "select all the rows from the array a and then select the first row". Similarly, a[0][:] means "select the first row of a and then select this entire row again". This is why you could replace the rows successfully, but not the columns - it's necessary to make a selection for axis 1, not just axis 0.

Sign up to request clarification or add additional context in comments.

Comments

9

You can do something like this:

import numpy as np

a = np.zeros((2,2), dtype=np.int)
a[:,0] = np.ones((1,2), dtype=np.int)

Please refer to Accessing np matrix columns

Comments

5

Select the intended column using a proper indexing and just assign the value to it using =. Numpy will take care of the rest for you.

>>> a[::,0] = 1
>>> a
array([[1, 0],
       [1, 0]])

Read more about numpy indexing.

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.