python - 将 NumPy 数组的指定元素转换为新值

标签 python arrays numpy

我想将 NumPy 数组 A 的指定元素:1、5 和 8 转换为 0。

所以我做了以下事情:

import numpy as np

A = np.array([[1,2,3,4,5],[6,7,8,9,10]])

bad_values = (A==1)|(A==5)|(A==8)

A[bad_values] = 0

print A

是的,我得到了预期的结果,即新数组。

然而,在我的现实世界问题中,给定的数组(A)非常大,而且也是二维的,并且要转换为 0 的 bad_values 的数量也太多。因此,我尝试了以下方法:

bads = [1,5,8] # Suppose they are the values to be converted into 0

bad_values = A == x for x in bads  # HERE is the problem I am facing

我该怎么做?

那么,剩下的当然就和以前一样了。

A[bad_values] = 0

print A

最佳答案

如果您想获取数组A中出现错误值的索引,您可以使用in1d来找出bads中的值:

>>> np.in1d(A, bads)
array([ True, False, False, False,  True, False, False,  True, False, False], dtype=bool)

因此,您只需编写 A[np.in1d(A, bads)] = 0 即可将 A 的坏值设置为 0.

编辑:如果您的数组是二维的,一种方法是使用 in1d 方法,然后重新整形:

>>> B = np.arange(9).reshape(3, 3)
>>> B
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

>>> np.in1d(B, bads).reshape(3, 3)
array([[False,  True, False],
       [False, False,  True],
       [False, False,  True]], dtype=bool)

所以你可以执行以下操作:

>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
       [3, 4, 0],
       [6, 7, 0]])

关于python - 将 NumPy 数组的指定元素转换为新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084671/

相关文章:

python - 修剪/缩尾标准差

python - 如果在 pygame 中没有按下箭头键,则继续循环

python - 如何加速递归算法

python - 为什么调用带有 -m 选项的模块会将 sys.path[0] 设置为空字符串?

具有多个条件的Python numpy数组迭代图像

python - Python 中正向替换的数值稳定性

python - 大量 NDB 实体的更新失败

java - 将二维数组中的所有元素向下移动

arrays - PLpgSQL:将每条记录存储在For循环中并返回json

python - 添加到常规 numpy ndarray 时调用 scipy.sparse __add__ 方法?