469,275 Members | 1,835 Online

# Numpy, adding a row to a matrix

Hello,
I have a numpy array (2 rows 3 colums)

import numpy
a=numpy.array( [ [1,2,3] , [3,3,1] ])

I wish to add a row, this is how i do it

s=a.shape
numpy.resize(a,s+1,s)
a[s]=new row vector.

Q: Is this a costly operation? What happens if i have to it several
(and unknown) number of times?
is there a simpler way to add a row?

Saptarshi
Jun 27 '08 #1
2 23217 sapsi wrote:
Hello,
I have a numpy array (2 rows 3 colums)

import numpy
a=numpy.array( [ [1,2,3] , [3,3,1] ])

I wish to add a row, this is how i do it

s=a.shape
numpy.resize(a,s+1,s)
a[s]=new row vector.

Q: Is this a costly operation?
It can be if you have large arrays.
What happens if i have to it several
(and unknown) number of times?
is there a simpler way to add a row?
numpy.vstack([a, newrow])

Generally speaking, you shouldn't resize numpy arrays. If you need to construct
an array by appending, build up a list instead and use vstack() (or hstack() or
dstack() or column_stack() or concatenate() depending on the geometry).

We also have a numpy mailing list, which you should direct future numpy
questions to:

http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
an underlying truth."
-- Umberto Eco

Jun 27 '08 #2
Hello,
Thank you. Yes, I will post to the numpy mailing list in future.
Regards
Saptarshi
On Jun 9, 4:04*pm, Robert Kern <robert.k...@gmail.comwrote:
sapsi wrote:
Hello,
I have a numpy array (2 rows 3 colums)
import numpy
a=numpy.array( *[ [1,2,3] , [3,3,1] ])
I wish to add a row, this is how i do it
s=a.shape
numpy.resize(a,s+1,s)
a[s]=new row vector.
Q: Is this a costly operation?

It can be if you have large arrays.
What happens if i have to it several
(and unknown) number of times?
is there a simpler way to add a row?

numpy.vstack([a, newrow])

Generally speaking, you shouldn't resize numpy arrays. If you need to construct
an array by appending, build up a list instead and use vstack() (or hstack() or
dstack() or column_stack() or concatenate() depending on the geometry).

We also have a numpy mailing list, which you should direct future numpy
questions to:

* *http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma