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

查看:59
本文介绍了更改不在索引列表中的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天全站免登陆