6

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
3
  • 1
    Just for reference: Looking at numpy source fromfunction just creates indices array and passes it to user function. So i and j are arrays, not ints. Commented May 28, 2013 at 20:15
  • @mg007 I believe the function will unbox those, however. Commented May 28, 2013 at 20:20
  • You can see how it performs that task in this similar question: stackoverflow.com/questions/400739/what-does-mean-in-python Commented May 28, 2013 at 20:23

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

passing the function through np.vectorize is the trick documentation fails to point out, thank you so much
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.14

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.