I want to replace certain columns in a multi-dimensional array with the value that I have. I tried the following.
cols_to_replace = np.array([1, 2, 2, 2])
original_array = np.array([[[255, 101, 51],
[255, 101, 153],
[255, 101, 255]],
[[255, 153, 51],
[255, 153, 153],
[255, 153, 255]],
[[255, 203, 51],
[255, 204, 153],
[255, 205, 255]],
[[255, 255, 51],
[255, 255, 153],
[255, 255, 255]]], dtype=int)
Replace just the cols with (0, 0, 255)
I was hoping that I can index all the columns using the array cols_to_replace
original_array[:, cols_to_replace] = (0, 0, 255)
This gave a wrong answer!
Unexpected output.
array([[[255, 101, 51],
[ 0, 0, 255],
[ 0, 0, 255]],
[[255, 153, 51],
[ 0, 0, 255],
[ 0, 0, 255]],
[[255, 203, 51],
[ 0, 0, 255],
[ 0, 0, 255]],
[[255, 255, 51],
[ 0, 0, 255],
[ 0, 0, 255]]])
My expected output is
array([[[255, 101, 51],
[ 0, 0, 255],
[255, 101, 255]],
[[255, 153, 51],
[255, 153, 153],
[ 0, 0, 255]],
[[255, 203, 51],
[255, 204, 153],
[ 0, 0, 255]],
[[255, 255, 51],
[255, 255, 153],
[ 0, 0, 255]]])
What is really happening?
How do I accomplish what I am trying to do (that is access, col 1, col 2, col 2, col 2 in each of these rows and replace the values.
If I want to delete those columns, is there a
numpyway to do it?
original_array[np.arange(cols_to_replace.size), cols_to_replace] = 0, 0, 255:to access all the rows not working? You could list down as an answer for me to accept it.:to anarangewe switch the zeroth dimension to advanced indexing, so that cols_to_replace` can act level by level. - deleting is a bit more tricky