1

Is there a numpy manner to compute next problem? I really want to use numpy because the array is much much larger than this example.

a = np.array([[5, 2, 3, 4], [6, 3, 6, 6], [9, 1, 4, 6]])
b = np.min(a,1)

print(a)
# [[5 2 3 4]
#  [6 3 6 6]
#  [9 1 4 6]]

print(b)
# [2 3 1]

print(a-b) # ValueError: operands could not be broadcast together with shapes (3,4) (3,) 

# What I want:
# [[3 0 1 2]
#  [3 0 3 3]
#  [8 0 3 5]]
4
  • 1
    Use keepdims=True with np.min. Refer to docs. Commented Sep 5, 2017 at 13:38
  • Thanks for the quick response, that solves the problem. Now I see that I had to reshape the array. Commented Sep 5, 2017 at 13:41
  • You don't need to reshape if you keep the no. of dims intact with the min reduction. Commented Sep 5, 2017 at 13:48
  • I understand, it's more logical to keep the dimensions intact by setting the flag. Commented Sep 5, 2017 at 13:52

2 Answers 2

2

You can do this:

print(a-b.reshape(-1,1))
Sign up to request clarification or add additional context in comments.

Comments

2

This will do the job:

print(a-b.reshape(len(b),-1))

This prints

array([[3, 0, 1, 2],
       [3, 0, 3, 3],
       [8, 0, 3, 5]])

Comments

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.