python - 功能变化不大。面具。 Python

标签 python numpy mask

我有以下功能:

def delta(r, dr):
   res = np.zeros(r.shape)
   mask1 = (r >= 0.5*dr) & (r <= 1.5*dr)
   res[mask1] = (5-3*np.abs(r[mask1])/dr \
    - np.sqrt(-3*(1-np.abs(r[mask1])/dr)**2+1))/(6*dr)
   mask2 = np.logical_not(mask1) & (r <= 0.5*dr)
   res[mask2] = (1+np.sqrt(-3*(r[mask2]/dr)**2+1))/(3*dr)
   return res

哪里rnumpy.array尺寸(shape[0],shape[1])dr是单个值。 我想修改函数使 dr也是一个与 r 大小相同的数组对于 r 的每个值从 dr 中获取类似值.

例如r[0,0]搭配dr[0,0] , r[0,1]dr[0,1]等等。 有什么想法吗?

最佳答案

您可以将 2D 掩码与输入数组相乘,这实际上是掩码,从而执行计算,生成 2D 数组,而不是迄今为止使用 bool 索引的 1D 数组。唯一的区别是将值设置到输出数组中,为此您需要屏蔽要设置的数组和从中选择值的 2D 计算数组。

实现看起来像这样 -

# Initialize output array   
res = np.zeros(r.shape)

# Get mask1 and compute values for all elements and use the mask to set only
# TRUE positions with the computed values
mask1 = (r >= 0.5*dr) & (r <= 1.5*dr)
V1 = (5-3*np.abs(r*mask1)/dr - np.sqrt(-3*(1-np.abs(r*mask1)/dr)**2+1))/(6*dr)
res[mask1] = V1[mask1]

# Similarly for mask2 and the computations with that mask
mask2 = np.logical_not(mask1) & (r <= 0.5*dr)
V2 = (1+np.sqrt(-3*(r*mask2/dr)**2+1))/(3*dr)
res[mask2] = V2[mask2]

关于python - 功能变化不大。面具。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781420/

相关文章:

opencv - NumPy/OpenCV 2 : how to enumerate all pixels from region?

python - 如何使用 (2,3) 索引数组和 (2,3) 新值数组填充 (2,3,4) 数组的值

c# - 为什么要屏蔽基类成员?

python - 如何在 geopandas map 上添加 "North Arrow"

python - 如何从变量中获取数据并将其放入另一个变量中

python - Tensorflow 在忽略范围名称或进入新范围名称时恢复

python - 如何计算 scipy 稀疏矩阵行列式而不将其变为密集?

python - 具有值屏蔽的 groupby

css - 图像在较小的屏幕上显示不正确

python - 如何使用 Xlwings 向 Excel 中的单元格添加注释