Broadcasting 2D array in specific columns in Python

449 views Asked by At

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

There are 2 answers

1
Grayrigel On

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]])
0
Shaoqi Chen On

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.