Wiz123
Wiz123

Reputation: 920

Appending matrices

Suppose I have a matrix. I delete an entire row and after doing so, I want to append the deleted row to the reduced matrix. How can I do this?

import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
A1=np.delete(A,1,0)
A2=A[1,:]
np.append(A1,A2,0)

But this is showing error.

Any suggestion?

Upvotes: 2

Views: 104

Answers (4)

when appending keep the arrays in the same dimension

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
A1=np.delete(A,1,0)
#a2 must be the same dimension as a1
A2=[A[1,:]]
print(np.append(A1,A2,axis=0))

output:

[[1 2 3]
 [7 8 9]
 [4 5 6]]

Upvotes: 0

NPE
NPE

Reputation: 500307

How about:

def move_row_to_end(A, row):
  return A[range(row) + range(row + 1, A.shape[0]) + [row]]

A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print move_row_to_end(A, 1)

Upvotes: 1

tiago
tiago

Reputation: 23492

When you do np.delete it returns the array without the deleted row, not the deleted row. So your A1 has actually two rows instead of one, and that's why it's failing.

To achieve what you want, this should do it:

A1 = A[1]
A = np.delete(A, 1, 0)
result = np.append(A, A1[np.newaxis, :], 0)

and this result will contain:

array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])

Was this what you wanted?

Note the use of np.newaxis is necessary to make the single-row array A1 of the same shape as the array to append (because np.append requires arrays to have the same number of dimensions).

Upvotes: 1

Jon
Jon

Reputation: 12874

You can try vstack instead: Stack arrays in sequence vertically (row wise). http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html

In [33]: np.vstack([A1, A2])
Out[33]: 
array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])

Upvotes: 1

Related Questions