python - 将 numpy 数组值从零更改为 -1

标签 python python-3.x numpy

我有一个由随机排列的 1 和 0 组成的 numpy 数组。

numpy.array([[0,1,1],[1,0,0]]) 

如何在不改变那些的情况下将零更改为 -1?

最佳答案

正如 the comments 中已经指出的那样基本上有两种方法可以替换值。使用 boolean array indexing就地更改值:

>>> import numpy as np
>>> arr = np.array([[0,1,1],[1,0,0]])
>>> arr[arr==0] = -1
>>> arr 
array([[-1,  1,  1],
       [ 1, -1, -1]])

您可能想要检查 arr == 0(创建掩码)和 arr[arr == 0](仅获取值掩码为 True 的数组,在本例中值为 0)以了解发生了什么。

或者,如果你想创建一个数组的副本,并用替换的值创建一个 np.where :

>>> np.where(arr==0, -1, arr)
array([[-1,  1,  1],
       [ 1, -1, -1]])

这将创建一个新数组并在条件(第一个参数)为真时使用第二个参数,否则使用第二个参数项。

关于python - 将 numpy 数组值从零更改为 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42875900/

相关文章:

python - 我可以在没有嵌套循环的情况下根据元组的元素比较两组元组吗?

python - 如何重命名我的图像?

python - 将 numpy 数组转换为 C 连续顺序的最便宜方法?

numpy - 从 Pycharm 运行 numpy

python - Python 中特定范围内的值的数量

python - 继承时避免 __init__ 和 super 样板

python - 无法识别 DataFrame 中的列。关键字错误: 'Date'

python - Numpy 索引第一个 bool 值

python - 如何在 python 中找到所有可能的正则表达式匹配项?

python - 使用 pandas 将 int 转换为 timedelta