Python 更改不在索引列表中的 NumPy 数组的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16940895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:03:03  来源:igfitidea点击:

Change the values of a NumPy array that are NOT in a list of indices

pythonarraysnumpyreplacemultidimensional-array

提问by Saullo G. P. Castro

I have a NumPy array like:

我有一个 NumPy 数组,如:

a = np.arange(30)

I know that I can replace the values located at positions indices=[2,3,4]using for instance fancy indexing:

我知道我可以indices=[2,3,4]使用例如花式索引替换位于位置的值:

a[indices] = 999

But how to replace the values at the positions that are not in indices? Would be something like below?

但是如何替换不在 中的位置的值indices?会像下面这样吗?

a[ not in indices ] = 888

采纳答案by mgilson

I don't know of a clean way to do something like this:

我不知道做这样的事情的干净方法:

mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool)
mask[indices] = False
a[~mask] = 999
a[mask] = 888

Of course, if you prefer to use the numpy data-type, you could use dtype=np.bool_-- There won't be any difference in the output. it's just a matter of preference really.

当然,如果您更喜欢使用 numpy 数据类型,则可以使用dtype=np.bool_-- 输出不会有任何差异。这真的只是一个偏好问题。

回答by kirelagin

Obviously there is no general notoperator for sets. Your choices are:

显然not,集合没有通用运算符。您的选择是:

  1. Subtracting your indicesset from a universal set of indices (depends on the shape of a), but that will be a bit difficult to implement and read.
  2. Some kind of iteration (probably the for-loop is your best bet since you definitely want to use the fact that your indices are sorted).
  3. Creating a new array filled with new value, and selectively copying indices from the old one.

    b = np.repeat(888, a.shape)
    b[indices] = a[indices]
    
  1. indices从一组通用索引中减去您的集合(取决于 的形状a),但这将有点难以实现和阅读。
  2. 某种迭代(可能for-loop 是您最好的选择,因为您肯定想使用索引已排序的事实)。
  3. 创建一个填充新值的新数组,并有选择地复制旧数组的索引。

    b = np.repeat(888, a.shape)
    b[indices] = a[indices]
    

回答by aaren

Only works for 1d arrays:

仅适用于一维数组:

a = np.arange(30)
indices = [2, 3, 4]

ia = np.indices(a.shape)

not_indices = np.setxor1d(ia, indices)
a[not_indices] = 888

回答by Alexey Trofimov

Just overcome similar situation, solved this way:

刚刚克服了类似的情况,这样解决了:

a = np.arange(30)
indices=[2,3,4]

a[indices] = 999

not_in_indices = [x for x in range(len(a)) if x not in indices]

a[not_in_indices] = 888