如何对numpy数组中的某些数字进行一些数学运算?

时间:2019-08-09 09:44:05

标签: python numpy matrix

我有一个numpy数组/矩阵。 我愿意对此矩阵的非零元素进行一些操作。

假设元素(i,j)是a。 如果a为非零值,则将a替换为:1-1 /(2 * a)*(1-exp(-2 * a))。

我知道可以通过使用for循环来完成,但是在大规模情况下会花费太多时间。 感谢您的帮助。 :D

2 个答案:

答案 0 :(得分:2)

您可以使用np.where有条件地选择0或计算结果。我们还可以抑制由零除触发的NumPy警告(无论如何我们都丢弃这些值,因此可以放心地忽略该警告)。

另一种方法是屏蔽蒙版数组中的所有零元素,而第三种方式是首先索引所有有效元素,然后仅对那些元素进行计算:

A = np.random.rand(300, 400)
A *= np.random.randint(2, size=A.shape)

def using_where(A):
    with np.errstate(divide='ignore', invalid='ignore'):
        return np.where(
            A == 0,
            0,
            1 - (1/(2 * A)) * (1 - np.exp(-2 * A))
        )

def using_ma(A):
    mA = np.ma.masked_equal(A, 0)
    mA = 1 - (1/(2 * mA)) * (1 - np.exp(-2 * mA))
    return mA.filled(0)

def using_mask(A):
    A = A.copy()  # we are modifying A inplace. To make this function pure we need to work on a copy of A
    mask = A != 0
    A[mask] = 1 - (1/(2 * A[mask])) * (1 - np.exp(-2 * A[mask]))
    return A

%timeit using_where(A)
# 5.51 ms ± 329 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit using_ma(A)
# 20.3 ms ± 508 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit using_mask(A)
# 6.61 ms ± 301 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

如您所见,np.where方法是最快的。

答案 1 :(得分:1)

如果您愿意进行某些操作,则可以使用np.where条件运算符:)

尝试以下方法
a = np.where(np.equal(a, 0), a, 1-1/(2 * a )*(1-exp(-2*a)))