how to change some rows of matrices together?

Issue

is it possible to change some rows of matrices together?
for example, I have a matrix ‘a’ like this :

a=np.array( [[1,2],[3,4],[5,6],[7,8]] )

and another matrix ‘b’ like this:

b=np.array( [[9,10],[11,12],[13,14],[15,16]] )  

now I want to change them from the third row. so ‘a’ and ‘b’ will be like this:

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

could you help me to do this?
thanks.

Solution

np.vstack is your friend

new_a = np.vstack((a[:2,:], b[2:,:]))
new_b = np.vstack((b[:2,:], a[2:,:]))


array([[ 1,  2],
       [ 3,  4],
       [13, 14],
       [15, 16]])

array([[ 9, 10],
       [11, 12],
       [ 5,  6],
       [ 7,  8]])

Answered By – Sembei Norimaki

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published