我有一个arorg
这样的数组:
import numpy as np
arorg = np.array([[-1., 2., -4.], [0.5, -1.5, 3]])
和另一个values
如下所示的数组:
values = np.array([1., 0., 2.])
values
条目数与arorg
列数相同。
现在我想将函数应用于条目或arorg
取决于它们是正数还是负数:
def neg_fun(val1, val2):
return val1 / (val1 + abs(val2))
def pos_fun(val1, val2):
return 1. / ((val1 / val2) + 1.)
由此,val2
在(绝对)值arorg
和val1
-这是棘手的部分-来自values
; 如果我申请pos_fun
和neg_fun
列i
中arorg
,val1
应该是values[i]
。
我目前实现如下:
ar = arorg.copy()
for (x, y) in zip(*np.where(ar > 0)):
ar.itemset((x, y), pos_fun(values[y], ar.item(x, y)))
for (x, y) in zip(*np.where(ar < 0)):
ar.itemset((x, y), neg_fun(values[y], ar.item(x, y)))
这给了我想要的输出:
array([[ 0.5 , 1. , 0.33333333],
[ 0.33333333, 0. , 0.6 ]])
由于我必须经常做这些计算,我想知道是否有更有效的方法来做到这一点。就像是
np.where(arorg > 0, pos_fun(xxxx), arorg)
会很棒,但我不知道如何正确传递参数(xxx
)。有什么建议么?
正如问题中所暗示的,这是一个使用np.where
.
首先,我们使用函数实现的直接转换来为正例和负例生成值/数组。然后,使用正值掩码,我们将使用np.where
.
因此,实现看起来会沿着这些方向 -
# Get positive and negative values for all elements
val1 = values
val2 = arorg
neg_vals = val1 / (val1 + np.abs(val2))
pos_vals = 1. / ((val1 / val2) + 1.)
# Get a positive mask and choose between positive and negative values
pos_mask = arorg > 0
out = np.where(pos_mask, pos_vals, neg_vals)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句