在 NumPy 数组的每个单元格处对函数进行有效评估 [英] Efficient evaluation of a function at every cell of a NumPy array

查看:18
本文介绍了在 NumPy 数组的每个单元格处对函数进行有效评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 NumPy 数组 A,什么是最快的/将相同函数f应用到每个单元格的最有效方法?

Given a NumPy array A, what is the fastest/most efficient way to apply the same function, f, to every cell?

  1. 假设我们将把 f(A(i,j)) 分配给 A(i,j).

函数 f 没有二进制输出,因此 mask(ing) 操作无济于事.

The function, f, doesn't have a binary output, thus the mask(ing) operations won't help.

明显的"双循环迭代(通过每个单元格)是最佳解决方案吗?

Is the "obvious" double loop iteration (through every cell) the optimal solution?

推荐答案

你可以 将函数向量化,然后在每次需要时将其直接应用于 Numpy 数组:

You could just vectorize the function and then apply it directly to a Numpy array each time you need it:

import numpy as np

def f(x):
    return x * x + 3 * x - 2 if x > 0 else x * 5 + 8

f = np.vectorize(f)  # or use a different name if you want to keep the original f

result_array = f(A)  # if A is your Numpy array

在向量化时直接指定显式输出类型可能更好:

It's probably better to specify an explicit output type directly when vectorizing:

f = np.vectorize(f, otypes=[np.float])

这篇关于在 NumPy 数组的每个单元格处对函数进行有效评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆