2个numpy数组之间的计算

Calculations between 2 numpy arrays

我正在编写一个对 2 个 numpy 数组进行计算的程序,但只对不少于 4 的元素执行计算,例如:

Input:
array1 = np.array([[4, 4, 6], [2, 3, 9]])
array2 = np.array([1, 1, 2])

Output:
([5, 9])

Explanation:
For the first element, the calculation is (4*1 + 4*1 + 6*2) / (1 + 1 + 2) = 5
For the second element, the calculation is (9*2) / 2 = 9 (because 2 and 3 are less than 4)

因此,我尝试将小于 4 的数字转换为 0 的分子:

def function(array1, array2):
    return np.sum(np.where(array1 >= 4, array1 * array2, 0), axis=1)

但是对于分母,如果array1中的元素小于4,我不知道如何将数字转换为0。谁能帮我解决这个问题?感谢您的帮助!

您可能需要使 array2 与 array1 的大小相同:

>>> array1 = np.array([[4, 4, 6], [2, 3, 9]])
>>> array2 = np.array([1, 1, 2])
>>> array2 = array2 * (array1 >= 4)
>>> array2
array([[1, 1, 2],
       [0, 0, 2]])
>>> (array1 * array2).sum(-1) / array2.sum(-1)
array([5., 9.])

您必须按照计算分子的方式计算分母。
要注意的一件事是除以0(你的输入数据不会触发那种情况,但我加了一些确实如此)。

这是一个例子(我相信有更快(更好)的方法来完成这个)。

code00.py:

#!/usr/bin/env python

import sys

import numpy as np


def divide(a0, a1):
    num = np.sum(np.where(a0 >= 4, a0 * a1, 0), axis=1)
    #print("num:", num)
    denom = np.sum(np.where(a0 >= 4, a1, 0), axis=1)
    #print("denom:", denom)
    errs = np.geterr()
    np.seterr(invalid="ignore")
    ret = np.where(denom == 0, 0, num / denom)  # A warning will pop up even if no division by 0 is actually performed
    if errs["invalid"] != "ignore":
        np.seterr(invalid=errs["invalid"])
    return ret


def main(*argv):
    test_sets = (
        (
            ((4, 4, 6), (2, 3, 9)),
            (1, 1, 2),
        ),
        (
            ((4, 1, 4), (1, 1, 2)),  # 2nd element will yield 0 for both numerator and denominator
            (1, 1, 2),
        ),
    )

    for test_set in test_sets:
        arrs = [np.array(e) for e in test_set]
        print(divide(*arrs))


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q072504478]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32

[5. 9.]
[4. 0.]

Done.
import numpy as np
array1 = np.array([[4, 4, 6], [2, 3, 9]])
array2 = np.array([1, 1, 2])

array1_consider = np.where(array1<4,0,1)
array2 = array1_consider*array2

nominator = np.sum(array1*array2,axis=1)
denominator = np.sum(array2,axis=1)

result = nominator/denominator
print(result)

您可以使用 where 屏蔽您的数据,然后计算点积。对于你的分母,使用掩码来传播每行的因子,而不是 sum 和除法:

mask = array1>=4
b = np.where(mask, array1, 0)
# array([[4, 4, 6],
#        [0, 0, 9]])

d = (array2*mask).sum(1)
# array([4, 2])

(b@array2)/d
# array([5., 9.])

两行:

mask = array1>=4
out = np.where(mask, array1, 0)@array2/(array2*mask).sum(1)