0

I have an array like this:

A = np.array([[ 1, 2, 3, 4, 5],
              [ 6, 7, 8, 9, 10],
              [11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20]])

What I want to do is add 1 to each value in the first and last column. I want to understand broadcasting (avoid loops), by using this and appropriate vector, but I have tried but it doesn't work. Expected results:

A = np.array([[ 2, 2, 3, 4, 6],
                   [ 7, 7, 8, 9, 11],
                   [12, 12, 13, 14, 16],
                   [17, 17, 18, 19, 21]])
2

2 Answers 2

1

You can use numpy indexing to do this. Try this:

# 0 is the first and -1 is the last column
A[:,[0,-1]]  = A[:,[0,-1]]+1  

Or

A[:,(0,-1)]  = A[:,(0,-1)]+1 

Or

A[:,[0,-1]]+=1

Or

A[:,(0,-1)]+=1 

Output in either case:

array([[ 2,  2,  3,  4,  6],
       [ 7,  7,  8,  9, 11],
       [12, 12, 13, 14, 16],
       [17, 17, 18, 19, 21]])
Sign up to request clarification or add additional context in comments.

1 Comment

Added an answer. Let me know if it works for you. If it please checkmark/accept the answer.
0

You can use vector [1,0,0,0,1] and python will do broadcasting for you.

b = np.array([1,0,0,0,1])
A + b
array([[ 2,  2,  3,  4,  6],
       [ 7,  7,  8,  9, 11],
       [12, 12, 13, 14, 16],
       [17, 17, 18, 19, 21]])

If you would like to know how broadcasting works, you can simply try to broadcast once by yourself.

b = np.array([1,0,0,0,1])
B = np.tile(b,(A.shape[0],1))  
array([[1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1]])
A + B

Same result.

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.