0

This is an example of my error. Say i created a numpy array

X = np.zeros((1000, 50))

Where 1000 is the features (rows) and 50 is the examples (columns)

Since i am adding examples one by one i will have to replace columns in the array 1 by 1 to get the final feature array. I tried this:

X[:,i] = example

where example is of size (1000, 1), and i is iterated for every example. This does not work because X[:,i] is of shape (1000,), a rank 1 array. How do i code it so that each example replaces a row of the X array without throwing the broadcast error. Thank you.

1
  • 2
    X[:,i] = example.reshape(1000) ? Commented Jan 29, 2019 at 22:11

1 Answer 1

1

Reshape your vector before assigning it.

X[:,i] = example.reshape(-1,)

This will suppress the second dimension and turn example into shape (1000,)

Or, avoiding assigning one by one in the loop you can put all of your arrays in a list and then call np.array on your list and transpose it to have them as columns. This will probably work better if you can construct your list of arrays in a list comprehension.

Example:

arrs = [np.random.randint(10, size=5) for _ in range(5)]
X = np.array(arrs).T
Sign up to request clarification or add additional context in comments.

1 Comment

First solution worked, I will try to use a method like the second in the future, Thanks!

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.