I have an array created with numpy:
matriz = numpy.matrix([]);
I try to insert rows in a loop (something like):
for i in range(3) : matriz = numpy.insert(matriz, i, [i + 1, 0, 0])
I expected the result to be:
matrix([[1, 0, 0], [2, 0, 0], [3, 0, 0]])
However I get:
matrix([[ 1., 2., 3., 0., 0., 0., 0., 0., 0.]])
What am I doing wrong?
This happens because you do not indicate the axis to which you want to add the data (
0
forfilas
and1
forcolumnas
). If this parameter is not indicated the array/matrix is flattened first as you can see in the documentation ofnumpy.insert()
:The correct syntax would be:
The problem is that you are trying to add a row with three columns to a 1x0 matrix. That throws an error. The solution may be to initialize a 3 row but empty array. For this we can use
numpy.empty
:Anyway there are more efficient ways to do this like:
I specify the data type with
dtype
because if I don't, it will be thefloat
default.In both cases we get:
Although the first method (using
np.insert()
) is much more inefficient than the second (list comprehensions), I get the following results for adding 100,000 rows:np.insert()
: 9.337375402450562 secondslist comprehensions
: 0.07504963874816895 seconds