28

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.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Jika
  • 1,556
  • 4
  • 16
  • 27

3 Answers3

57

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.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
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

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Zhiya
  • 610
  • 2
  • 7
  • 22
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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188