python - 如何根据 True 和 False 语句比较两个 numpy 数组

标签 python numpy

self.x = np.array( [np.random.uniform( -5, 5 ) for _ in xrange( 100 )] )
v = np.array( [np.random.uniform( -5, 5 ) for _ in xrange( 100 )] )
good = np.random.uniform(0,1,5) < 0.5
good = good.reshape(1,self.x.shape[1])
self.x[good] = v[good]
u = self.x[good]

假设good[False True True True True]u 向量丢弃第一个值为 False 的值,其余值为 True 的值被替换。但我希望它保留 self.x

的先前值

最佳答案

在我看来,您希望xv保持不变,但有第三个向量u,即 v 只要 goodTrue,但 x 在其他地方呢?为此,您可以使用函数np.where

这是一个例子:

x = np.arange(1,6)
v = 10*x
good = np.array([False, True, True, True, True])

In [690]: x
Out[690]: array([1, 2, 3, 4, 5])

In [691]: v
Out[691]: array([10, 20, 30, 40, 50])

In [692]: good
Out[692]: array([False,  True,  True,  True,  True], dtype=bool)

In [693]: u = np.where(good, v, x)

In [694]: u
Out[694]: array([ 1, 20, 30, 40, 50])

In [695]: x
Out[695]: array([1, 2, 3, 4, 5])

In [696]: v
Out[696]: array([10, 20, 30, 40, 50])

关于python - 如何根据 True 和 False 语句比较两个 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20618167/

相关文章:

python - `scipy.optimize.minimize` 中的 Jacobian 和 Hessian 输入

python - 如何找到等于 x 的不同长度数组的加权组合?

python - 曲线拟合为指数

python - 重复和选择函数的轻微变化的快速 Numpy 计算

python - python 中的 matplotlib - 使用 x 轴中的相应值和大数绘制图形

python - 如何在 IPython Notebook 中嵌入数据?

python - 使用 pandas TimeSeries 创建热图

python - 在 for 循环中引用数组

python - 模块 'pip._internal.download' 没有属性 'is_file_url'

python - 在 Tensorflow 模型中添加低层