假设我有一个二维数组。如何将函数应用于数组中的每个项目并用返回值替换该项目?此外,函数的返回将是一个元组,因此数组将变成 3d。
这是心中的代码。
def filter_func(item):
if 0 <= item < 1:
return (1, 0, 1)
elif 1 <= item < 2:
return (2, 1, 1)
elif 2 <= item < 3:
return (5, 1, 4)
else:
return (4, 4, 4)
myarray = np.array([[2.5, 1.3], [0.4, -1.0]])
# Apply the function to an array
print(myarray)
# Should be array([[[5, 1, 4],
# [2, 1, 1]],
# [[1, 0, 1],
# [4, 4, 4]]])
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以做到吗?一种方法是这样做np.array(list(map(filter_func, myarray.reshape((12,))))).reshape((2, 2, 3)),但这非常慢,特别是当我需要在形状数组 (1024, 1024) …