python - Numpy: add a vector to matrix column wise -


a out[57]:  array([[1, 2],        [3, 4]])  b out[58]:   array([[5, 6],        [7, 8]])  in[63]: a[:,-1] + b out[63]:  array([[ 7, 10],        [ 9, 12]]) 

this row wise addition. how add them column wise

in [65]: result out[65]:  array([[ 7,  8],        [11, 12]]) 

i don't want transpose whole array, add , transpose back. there other way?

add newaxis end of a[:,-1], has shape (2,1). addition b broadcast along column (the second axis) instead of rows (which default).

in [47]: b + a[:,-1][:, np.newaxis] out[47]:  array([[ 7,  8],        [11, 12]]) 

a[:,-1] has shape (2,). b has shape (2,2). broadcasting adds new axes on left default. when numpy computes a[:,-1] + b broadcasting mechanism causes a[:,-1]'s shape changed (1,2) , broadcasted (2,2), values along axis of length 1 (i.e. along rows) broadcasted.

in contrast, a[:,-1][:, np.newaxis] has shape (2,1). broadcasting changes shape (2,2) values along axis of length 1 (i.e. along columns) broadcasted.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -