How to replace a single column with a value in a numpy array?

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 with a value of 1 . I have done the following:

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

Contrariwise when I replace the strings it works with!

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

I have a large array, so I cannot replace the value by value.

+9
source share
3 answers

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 passed along this selected column, creating the desired array (there is no need to use the list [1, 1] , although you can).

Your syntax a[:][0] means "select all rows from array a , and then select the first row." Similarly, a[0][:] means "select the first line of a , and then select the entire line again." That's why you can successfully replace rows, but not columns - you need to make a choice for axis 1, and not just for axis 0.

+17
source

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) 

Refer to Accessing Np Matrix Columns

+4
source

Select the desired column using the correct indexing and just assign it a value using = . Numpy takes care of the rest for you.

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

Learn more about NumPy indexing .

+3
source

Source: https://habr.com/ru/post/1215015/


All Articles