Most efficient way to map function over numpy array

前端 未结 11 1514
庸人自扰
庸人自扰 2020-11-22 02:13

What is the most efficient way to map a function over a numpy array? The way I\'ve been doing it in my current project is as follows:

import numpy as np 

x          


        
11条回答
  •  醉梦人生
    2020-11-22 02:44

    squares = squarer(x)
    

    Arithmetic operations on arrays are automatically applied elementwise, with efficient C-level loops that avoid all the interpreter overhead that would apply to a Python-level loop or comprehension.

    Most of the functions you'd want to apply to a NumPy array elementwise will just work, though some may need changes. For example, if doesn't work elementwise. You'd want to convert those to use constructs like numpy.where:

    def using_if(x):
        if x < 5:
            return x
        else:
            return x**2
    

    becomes

    def using_where(x):
        return numpy.where(x < 5, x, x**2)
    

提交回复
热议问题