I am using np.fromfunction to create an array of a specific sized based on a function. It looks like this:
import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(f, (len(test), len(test)), dtype=int)
However, I receive the following error:
TypeError: only integer arrays with one element can be converted to an index
asked May 28, 2013 at 19:54
sdasdadas
25.5k20 gold badges70 silver badges152 bronze badges
1 Answer 1
The function needs to handle numpy arrays. An easy way to get this working is:
import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(np.vectorize(f), (len(test), len(test)), dtype=int)
np.vectorize returns a vectorized version of f, which will handle the arrays correctly.
answered May 28, 2013 at 20:03
Florian Rhiem
1,8281 gold badge15 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
blue
passing the function through
np.vectorize is the trick documentation fails to point out, thank you so muchJulian - BrainAnnex.org
Excellent trick! It ought to be in the docs. I had similar problem with trivial scenario
f = lambda i, j: 3.14 Running np.fromfunction(f, (2, 6)) would simply give me a scalar 3.14 ! By contrast, np.fromfunction(np.vectorize(f), (2, 6)) returns the expected 2x6 matrix whose entries are all 3.14lang-py
fromfunctionjust createsindicesarray and passes it to user function. Soiandjarearrays, notints.