简体   繁体   English

Numpy 将函数应用于数组

[英]Numpy apply function to array

For example, I have function:例如,我有功能:

f1 = lambda x: x % 2

If I want to modify array = np.linspace(0, 5, 6) I can do f1(array) .如果我想修改array = np.linspace(0, 5, 6)我可以做f1(array) Everything works as expected:一切都按预期工作:

[0. 1. 0. 1. 0. 1.]

If I change function to:如果我将功能更改为:

f2 = lambda x: 0
print(f2(array))

gives me 0 while I expected [0. 0. 0. 0. 0. 0.]给我0而我期望[0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] . [0. 0. 0. 0. 0. 0.] . How to achieve consistency?如何实现一致性?

You can use below code to achieve desirable output您可以使用下面的代码来实现理想的输出

import numpy as np
array = np.linspace(0, 5, 6)
f2 = lambda x: x-x
print(f2(array))

Slightly more explicit than previous answer :比以前的答案更明确:

import numpy as np
array = np.linspace(0, 5, 6)
f2 = lambda x: np.zeros_like(x)
print(f2(array))

Documentation for numpy.zeros_like : Return an array of zeros with the same shape and type as a given array. numpy.zeros_like文档:返回与给定数组具有相同形状和类型的零数组。

To iterate over an array, evaluate the function for every element, then store it to a resulting array, a list iterator works consistently:要迭代数组,对每个元素计算函数,然后将其存储到结果数组中,列表迭代器始终如一地工作:

import numpy as np
array = np.linspace(0, 5, 6)
f1 = lambda x: x % 2
f2 = lambda x: 0

print ([f1(x) for x in array])

[0.0, 1.0, 0.0, 1.0, 0.0, 1.0] [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]

print ([f2(x) for x in array])

[0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM