[英]Replace elements in a numpy ndarray accessed via index array
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)
仅将cols替换为(0,0,255
(0, 0, 255)
I was hoping that I can index all the columns using the array cols_to_replace
我希望我可以使用数组
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. 如何完成我要执行的操作(即在这些行的每一行中分别访问a,col 1,col 2,col 2,col 2并替换值)。
If I want to delete those columns, is there a numpy
way to do it? 如果我要删除这些列,是否有一种
numpy
方法?
Your expected output is produced by: 您的预期输出是由以下人员产生的:
>>> original_array[np.arange(cols_to_replace.size), cols_to_replace] = 0, 0, 255
This differs from your original approach because advanced indexing and slice indexing are evaluated "separately". 这与您的原始方法不同,因为高级索引和切片索引是“单独”评估的。 By changing
:
to an arange
we switch the zeroth dimension to advanced indexing, so that cols_to_replace
is paired element-by-element with 0, 1, 2, ...
in the zeroth coordinate. 通过改变
:
一个arange
我们切换第零尺寸的高级索引,使得cols_to_replace
配对元件逐元素与0, 1, 2, ...
第0坐标。
You can delete your selection using a mask like so: 您可以使用以下掩码删除选择:
>>> mask = np.ones(original_array.shape[:2], bool)
>>> mask[np.arange(cols_to_replace.size), cols_to_replace] = False
>>> original_array[mask].reshape(original_array.shape[0], -1, original_array.shape[2])
array([[[255, 101, 51],
[255, 101, 255]],
[[255, 153, 51],
[255, 153, 153]],
[[255, 203, 51],
[255, 204, 153]],
[[255, 255, 51],
[255, 255, 153]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.