python - 元素的 numpy 条件格式

标签 python arrays numpy pyqtgraph

我有一个 3D numpy 数组,想根据对另一个元素的条件测试来更改特定元素。 (应用程序是更改 RGBA 图像阵列的“alpha”以播放 3D pyqtgraph 图像中的透明度 - 理想情况下应该非常快)。

a= np.ones((2,4,5),dtype=np.int) #create a ones array
a[0,0,0] = 3 #change a few values
a[0,2,0] = 3
a[1,2,0] = 3
print(a)
>>>[[[3 1 1 1 1]
  [1 1 1 1 1]
  [3 1 1 1 1]]

 [[1 1 1 1 1]
  [1 1 1 1 1]
  [3 1 1 1 1]]]

现在我想有条件地测试最低维度的第一个元素(??),然后根据结果更改最后一个元素。

if a[0,:,:] > 1:   #this does not work - for example only - if first element > 1
    a[3,:,:]=255   #then change the last element in the same dimension to 255

print(a) #this is my idealized result
>>>[[[3 1 1 1 255]
  [1 1 1 1 1]
  [3 1 1 1 255]]

 [[1 1 1 1 1]
  [1 1 1 1 1]
  [3 1 1 1 255]]]

最佳答案

这似乎可以解决问题:

mask = a[:,:,0] > 1

a[:,:,4][mask] = 255

因此索引只需要稍微不同,然后它只是应用掩码的标准做法。

编辑 @Ophion 表明这写得更好:

a[mask,:,-1] = 255

关于python - 元素的 numpy 条件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22435947/

相关文章:

python - OpenPyXL 为整列设置 number_format

c - 排序数组的前 n 个元素

当存在 '\n' 时,C++ 输出重复行

python - 计算二维 Numpy 数组中数字对频率的最有效方法

python - 如何使用 SQLAlchemy 获取引用的实体?

python - Keras 模型给出的测试精度为 1.0

python - 通过它们在 python 中的接近度来聚类值(机器学习?)

javascript - 如何保存使用 AngularJS 中的 ng-repeat 填充的多个选择框中的值?

python-3.x - numpy 中的这个操作叫什么?

python - 顺时针对ndarray进行排序的Numpyic方法?