更改不在索引列表中的 NumPy 数组的值 [英] Change the values of a NumPy array that are NOT in a list of indices

查看:36
本文介绍了更改不在索引列表中的 NumPy 数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NumPy 数组,例如:

I have a NumPy array like:

a = np.arange(30)

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

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

a[indices] = 999

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

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

a[ not in indices ] = 888

推荐答案

我不知道有什么干净的方法来做这样的事情:

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

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

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 数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆