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.
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With