AnarKi
AnarKi

Reputation: 997

How to append last row from 2D array in Python

How can I append the last row of an array to itself ?

something like:

x= np.array([(1,2,3,4,5)])
x= np.append(x, x[0], 1)

Also, Could you explain why this way of working with vectors yields an error?

for i in range(3):
    x.append(0)

x
[0, 0, 0]

x= np.append(x, x[0],0) 

Which way of working with vectors would be best ? I am trying to work with 2D vectors as being a matrix, keeping in mind i would like to do some future matrix calculations like multiplication etc.

Upvotes: 1

Views: 2659

Answers (3)

hpaulj
hpaulj

Reputation: 231395

In [3]: x=np.array([(1,2,3,4,5)])
In [4]: x
Out[4]: array([[1, 2, 3, 4, 5]])
In [5]: x=np.append(x,x[0],1)
...
ValueError: all the input arrays must have same number of dimensions

x is (1,5), x[0] is (5,) - one is 2d, the other 1d.

In [11]: x=np.vstack([x,x[0]])
In [12]: x
Out[12]: 
array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])

this works because vstack changes the x[0] to 2d, e.g. (1,5), so it can concatenate it with x.

In [16]: x=np.concatenate([x, np.atleast_2d(x[-1,:])])
In [17]: x.shape
Out[17]: (3, 5)

We can use concatenate (or append) by first expanding x[-1,:] to 2d.

But in general repeated concatenation is a slow way of building an array.

For a list, repeated append like this works. But it does not work for arrays. For one thing, an array does not have an append method. And np.append function returns a new array. It does not change x in place.

In [19]: z=[]
In [20]: for i in range(3):
    ...:     z.append(0)
    ...:     
In [21]: z
Out[21]: [0, 0, 0]

Repeated append to a list is fine. Repeated append to an array is slow.

In [25]: z=[]
In [26]: for i in range(3):
    ...:     z.append(list(range(i,i+4)))

In [27]: z
Out[27]: [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
In [28]: np.array(z)
Out[28]: 
array([[0, 1, 2, 3],
       [1, 2, 3, 4],
       [2, 3, 4, 5]])

Upvotes: 2

mechanical_meat
mechanical_meat

Reputation: 169324

>>> np.append(x,x[-1:],0)
array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])

Upvotes: 1

dermen
dermen

Reputation: 5362

How about this:

np.append(arr=x, values=x[-1,None], axis=0)
#array([[1, 2, 3, 4, 5],
#       [1, 2, 3, 4, 5]])

Upvotes: 0

Related Questions