I was expecting np.fromfunction(lambda i: 1, (4,), dtype=int)
to return array([1, 1, 1, 1])
, but it returns the integer 1
instead. Can someone explain to me why numpy.fromfunction behaves that way? It seems to have something to do with the definition of the anonymous function (i.e., whether a parameter of the function is actually 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 isn't to create array([1, 1, 1, 1])
using this method. Rather, I'm making a call of the form
np.fromfunction(lambda i: **an expression that doesn't depend on i**, (n,))
In other words, I'm trying to initialize a numpy array by repeatedly making a call to some function. (There's a call to np.random.random() in that function so I'm not making redundant calls.)
@Warren Weckesser has explained why this is happening (the NumPy docs are a bit misleading here and nowhere make it clear that fromfunction
is expecting a vector). If you want to make your lambda
function work with fromfunction
you can vectorize it explicitly:
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'd have thought
np.ones(4, dtype=int)
(perhaps times a constant) would be better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With