Adding appending numpy arrays

2.3k views Asked by At

I'm currently trying to append multiple Numpy arrays together. Basically, what I want to do is to start from a (1 x m) matrix (technically a vector), and end up with a (n x m) matrix. So going from n (1 x m) matrices (vectors) to one (n x m) matrix (If that makes any sense). The ultimate goal with this is to write the matrix into a csv-file with the numpy.savetxt() function so I'll end up with a csv-file with n columns of m length.

The problem with this is that numpy.append() appends the vectors together into a (1 x 2m) vector. So let's say a1 and a2 are Numpy arrays with 10000 elements each. I'll append a2 into a1 by using the append function and simultaneously creating a new array called a, which contains both a1 and a2.

a=np.append(a1, a2, axis=0)
a.shape
>>(20000,)

What I want instead is for the shape to be of the form

>>(2, 10000)

or more generally

>>(n, m)

What should I do? Please note, that I want to continue adding the vectors into the array. Thanks for your time!

3

There are 3 answers

3
tmdavison On

you can use the transpose of numpy.column_stack

For example:

import numpy as np

a=np.array([1,2,3,4,5])
b=np.array([9,8,7,6,5])
c=np.column_stack((a,b)).T

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

print a.shape,b.shape,c.shape
>>> (5,) (5,) (2, 5)

EDIT:

you can keep adding columns like so:

d=np.array([2,2,2,2,2])
c=np.column_stack((c.T,d)).T
print c
>>> array([[1, 2, 3, 4, 5],
           [9, 8, 7, 6, 5],
           [2, 2, 2, 2, 2]])
print c.shape
>>> (3, 5)
0
farhawa On

This should work

a=np.append(a1, a2, axis=0).reshape(2,10000)
a.shape
>>(2,10000)
2
plonser On

In order to merge arrays vertically I would use np.vstack

import numpy as np

np.vstack((a1,a2))

However, from my point of view, numpy.array shouldn't be created using for loops and appending the new array to the old one. Instead, either you create first the whole numpy.array (nxm) and you write the data from the for loop into that array,

data = np.zeros((n,m))

for i in range(n):
    data[i] = ...

or you first create your array as an ordinary python list using append which you can transform at the end into an numpy.array.

data = []

for i in range(n):
    data.append(...)

data = np.asarray(data)