How to apply callback to NumPy array in Python

4 Answers

0 votes
# Vectorized operations (fastest & most NumPy‑like)

import numpy as np

# Input array
arr = np.array([1, 2, 3, 4])

# Vectorized operation (no loop needed)
result = arr * arr   # squares each element

print(result)  



'''
run:
 
[ 1  4  9 16]
 
'''

 



answered Mar 19 by avibootz
0 votes
# Using np.vectorize() (wraps the callback)

import numpy as np

# Define the callback function
def square(x):
    return x * x

arr = np.array([1, 2, 3, 4])

# Convert the function into a vectorized version
v_square = np.vectorize(square)

# Apply it to the array
result = v_square(arr)

print(result)  



'''
run:
 
[ 1  4  9 16]
 
'''
 

 



answered Mar 19 by avibootz
edited Mar 19 by avibootz
0 votes
# Using a list comprehension

import numpy as np

# Define the callback function
def square(x):
    return x * x

arr = np.array([1, 2, 3, 4])

# Apply callback using list comprehension
result = np.array([square(x) for x in arr])

print(result)  # [ 1  4  9 16 ]



'''
run:
 
[ 1  4  9 16]
 
'''

 



answered Mar 19 by avibootz
edited Mar 19 by avibootz
0 votes
# Using ufuncs (universal function)(fast)

import numpy as np

# Create a ufunc from a Python function
def square(x):
    return x * x

square_ufunc = np.frompyfunc(square, 1, 1)

arr = np.array([1, 2, 3, 4])
result = square_ufunc(arr)

print(result) 



'''
run:
 
[ 1  4  9 16]
 
'''

 



answered Mar 19 by avibootz
...