Unexpected result - numpy from function with constant functions

I expected np.fromfunction(lambda i: 1, (4,), dtype=int) will return array([1, 1, 1, 1]) , but instead it will return the integer 1 . Can someone explain to me why numpy.fromfunction behaves like this? This seems to have something to do with defining an anonymous function (i.e., is the function parameter really used).

 >>> import numpy as np >>> np.fromfunction(lambda i: i, (4,), dtype=int) array([0, 1, 2, 3]) >>> np.fromfunction(lambda i: 1, (4,), dtype=int) 1 >>> np.fromfunction(lambda i: 1 + i*0, (4,), dtype=int) array([1, 1, 1, 1]) 

EDIT: to clarify, my ultimate goal is not to create an array([1, 1, 1, 1]) with this method. Rather, I'm calling the form

 np.fromfunction(lambda i: **an expression that doesn't depend on i**, (n,)) 

In other words, I am trying to initialize a numpy array by repeatedly calling a function call. (There is a call to np.random.random () in this function, so I do not make redundant calls.)

+6
source share
2 answers

This is not explained in the documentation of the func argument in fromfunction docstring that func is called only once, with array arguments.

In this example

 np.fromfunction(lambda i: i, (4,), dtype=int) 

the anonymous function is called once, the argument i is an array [0, 1, 2, 3]. To check this, you can do:

 In [10] from __future__ import print_function In [11]: np.fromfunction(lambda i: print("i = %r" % (i,)), (4,), dtype=int) i = array([0, 1, 2, 3]) 

In this case, when func returns 1,

 np.fromfunction(lambda i: 1, (4,), dtype=int) 

because the value returned by one call is 1, the array created contains only 1.

It is not clear why you would like to use fromfunction to create an array of 1s instead of, say, np.ones , but in case you have something more complex in mind, here is one way to do this using np.ones_like :

 In [14]: np.fromfunction(lambda i: np.ones_like(i), (4,), dtype=int) Out[14]: array([1, 1, 1, 1]) 
+6
source

@Warren Weckesser explained why this is happening (NumPy docs are a bit misleading and nowhere make it clear that a fromfunction expects fromfunction ). If you want your lambda function to work with fromfunction , you can explicitly write it:

 In [1]: func = lambda i: 1 In [1]: vfunc = np.vectorize(func) In [2]: np.fromfunction(vfunc, (4,), dtype=int) Out[2]: array([1, 1, 1, 1]) 

But for this use case I would think

 np.ones(4, dtype=int) 

(maybe constant time) would be better.

+6
source

Source: https://habr.com/ru/post/980058/


All Articles