更改满足条件的NumPy数组的第n个条目 [英] Change n-th entry of NumPy array that fulfills condition

查看:127
本文介绍了更改满足条件的NumPy数组的第n个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NumPy数组 arr 和一个(反向)掩码掩码。为简单起见,我们假设它们都是1d。我想更改 arr 中的 n 非屏蔽值。

I have a NumPy array arr and an (inverse) mask mask. For simplicity let us assume they are both 1d. I want to change the nth non-masked value in arr.

一个例子:

import numpy as np
arr = np.arange(5)
mask = np.array((True, False, True, True, False))

不幸的是,

arr[mask][-1] = 100

我预计会返回

array([0, 1, 2, 100, 4])

无效关于非连续项目的NumPy数组视图中列出的原因。

解决方法是将允许的值存储在新变量中,更改相应的值,并将所有值复制回原始数组:

A workaround would be to store the allowed values in a new variable, change the respective value, and copy all values back into the original array:

tmp = arr[mask]
tmp[-1] = 100
arr[mask] = tmp

然而,这个解决方案很丑陋且效率低下,因为我必须复制许多我根本不想改变的值。

However, this solution is ugly and inefficient, since I have to copy many values that I do not want to change at all.

有没有人有一种优雅的方式来处理这类问题?我会对最通用的解决方案感兴趣,这样我就可以用 tmp 完成所有经典赋值操作。但是,如果有一种有效的方法仅适用于具体的案例,我仍然会对它感兴趣!

Does anyone have an elegant way to deal with this kind of problem? I would be interested in a maximally general solution, so that I could do all classic assignment operations with tmp. However, if there is an efficient way that works only for the concrete dscribed case, I would still be interested in it!

推荐答案

一种选择是使用 np.where 获取掩码条件为 True 。然后,您可以使用这些索引的子集索引到 arr 并进行分配:

One option would be to use np.where to obtain the set of indices where your mask condition is True. You can then index into arr using a subset of these indices and make your assignment:

# np.where returns a tuple of index arrays, one per dimension
arr[np.where(mask)[0][-1]] = 100

print(repr(arr))
# array([  0,   1,   2, 100,   4])

您可以将此方法与切片索引,布尔索引等结合使用。例如:

You could combine this approach with slice indexing, boolean indexing etc. For example:

arr[np.where(mask)[0][::-1]] = 100, 200, 300
print(repr(arr))
# array([300,   1, 200, 100,   4])

这篇关于更改满足条件的NumPy数组的第n个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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