3

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). 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.]. How to achieve consistency?

6
  • The return value of f2 is not an array. Nothing unexpected happening here. Commented Mar 4, 2019 at 11:26
  • 1
    you can use f2 = lambda x: x-x Commented Mar 4, 2019 at 11:27
  • I expected that f2 will iterate over array and evaluate every element then store it to a resulting array. Commented Mar 4, 2019 at 11:27
  • Python functions don't automatically iterate over their arguments; the expression x % 2 does (when x is an np.array). Commented Mar 4, 2019 at 11:28
  • you want the mod... np.mod(array, 2) => ,,, array([0., 1., 0., 1., 0., 1.]) Commented Mar 4, 2019 at 11:43

3 Answers 3

6

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))
Sign up to request clarification or add additional context in comments.

2 Comments

how about if the array was array of array ?
Thanks, @user702846 for your concern, in that case, we need some changes. The above code works for the mentioned case
3

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.

Comments

1

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]

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.