我正在编写一个程序,在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)

因此,我try 将小于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.])

Python相关问答推荐

在Python中,如何才能/应该使用decorator 来实现函数多态性?

如何在vercel中指定Python运行时版本?

如果AST请求默认受csref保护,那么在Django中使用@ system_decorator(csref_protect)的目的是什么?

在Pandas框架中截短至固定数量的列

剧作家Python:expect(locator).to_be_visible()vs locator.wait_for()

通过仅导入pandas来在for循环中进行多情节

将numpy数组存储在原始二进制文件中

Python 3.12中的通用[T]类方法隐式类型检索

TARete错误:类型对象任务没有属性模型'

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

使用@ guardlasses. guardlass和注释的Python继承

当独立的网络调用不应该互相阻塞时,'

如何使用pytest来查看Python中是否存在class attribution属性?

Pandas Loc Select 到NaN和值列表

Python导入某些库时非法指令(核心转储)(beautifulsoup4."" yfinance)

Python中的变量每次增加超过1

合并帧,但不按合并键排序

CommandeError:模块numba没有属性generated_jit''''

matplotlib图中的复杂箭头形状

在代码执行后关闭ChromeDriver窗口