[英]Broadcasting 2D array in specific columns in Python
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.我想要做的是将第一列和最后一列中的每个值加 1。 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]])
You can use numpy indexing
to do this.您可以使用 numpy indexing
来执行此操作。 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]])
You can use vector [1,0,0,0,1] and python will do broadcasting for you.你可以使用 vector [1,0,0,0,1] 并且 python 会为你做广播。
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.结果一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.