Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one column by a value in a numpy array?

Tags:

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.

like image 704
Jika Avatar asked Mar 09 '15 22:03

Jika


People also ask

How do you change a column in an array in Python?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.

How do I replace a row in a NumPy array?

To replace a row in an array we will use the slicing and * operator method. It will help the user for replacing rows elements. Firstly we will import the numpy library and then create a numpy array by using the np. array() function.

How do you change an element in an array Python?

Changing Multiple Array Elements In Python, it is also possible to change multiple elements in an array at once. To do this, you will need to make use of the slice operator and assign the sliced values a new array to replace them.


1 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 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.

like image 53
Alex Riley Avatar answered Oct 12 '22 19:10

Alex Riley