0

I have an issue with numpy arrays and I can't understand what I am doing wrong. I need to create a 100x100 matrix with random int (non zero) and the last row should be the combination of all previous rows. Here is my code:

non_zero_m = np.random.randint(0,10,(99,100))
arr = non_zero_m.sum(axis=0)
singular_m = np.concatenate((non_zero_m, arr))

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

I can't understand why python shows that arrays has different dimensions

2
  • 1
    What is arr.shape? Reread np.concatenate docs. Also look at np.vstack Commented Sep 15, 2021 at 0:45
  • stackoverflow.com/questions/53185055/… this may be helpful Commented Sep 15, 2021 at 1:00

1 Answer 1

1

The problem is that arr is a 1-dimensional array, and you are trying to concatenate it to a matrix (2-dimensional).

Just replace the second line with:

arr = non_zero_m.sum(axis=0).reshape(1, -1)

This reshapes arr to a 2-dimensonal array, such that the first axis has dimension 1 (thus making arr effectively a row vector), and the second axis has the required dimension to keep all of arr's elements (this is the meaning of -1 in this context).

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

1 Comment

Thank you so much!

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.