0

I have function predicton like

def predictions(degree):
  some magic,
  return an np.ndarray([0..100])

I want to call this function for a few values of degree and use it to populate a larger np.ndarray (n=2), filling each row with the outcome of the function predictions. It seems like a simple task but somehow I cant get it working. I tried with

for deg in [1,2,4,8,10]:
   np.append(result, predictions(deg),axis=1)

with result being an np.empty(100). But that failed with Singleton array array(1) cannot be considered a valid collection.

I could not get fromfunction it only works on a coordinate tuple, and the irregular list of degrees is not covered in the docs.

1
  • The singleton array(1) error message was originating from function predictions.` result = np.array([predictions(1), predictions(2), predictions(4),predictions(8)])` is working but not very nice.. Commented May 14, 2018 at 19:18

2 Answers 2

2

Don't use np.ndarray until you are older and wiser! I couldn't even use it without rereading the docs.

arr1d = np.array([1,2,3,4,5])

is the correct way to construct a 1d array from a list of numbers.

Also don't use np.append. I won't even add the 'older and wiser' qualification. It doesn't work in-place; and is slow when used in a loop.

A good way of building a 2 array from 1d arrays is:

alist = []
for i in ....:
    alist.append(<alist or 1d array>)
arr = np.array(alist)

provided all the sublists have the same size, arr should be a 2d array.

This is equivalent to building a 2d array from

np.array([[1,2,3], [4,5,6]])

that is a list of lists.

Or a list comprehension:

np.array([predictions(i) for i in range(10)])

Again, predictions must all return the same length arrays or lists.

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

3 Comments

I'm too old to get any wiser :-) but your answer has helped me. ndarray was not a free choice but a mandatory excercise outcome.
I (aesthetically) like the list comprehension, but not sure how expensive it is? (Performance is not my my top priority though).
List comprehension is generally a bit faster than the equivalent loop with append. The interpreter constructs a tighter set of bytecodes.
2

append is in the boring section of numpy. here you know the shape in advance

len_predictions = 100

def predictions(degree):
    return np.ones((len_predictions,))

degrees = [1,2,4,8,10]
result = np.empty((len(degrees), len_predictions))
for i, deg in enumerate(degrees):
    result[i] = predictions(deg)

if you want to store the degree somehow, you can use custom dtypes

1 Comment

This is the way +1. append is expensive (with anything), avoid where possible.

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.