-1

How do I concatenate properly two numpy vectors without flattening the result? This is really obvious with append, but it gets shamefully messy when turning to numpy.

I've tried concatenate (expliciting axis and not), hstack, vstack. All with no results.

In [1]: a
Out[1]: array([1, 2, 3])

In [2]: b
Out[2]: array([6, 7, 8])

In [3]: c = np.concatenate((a,b),axis=0)

In [4]: c
Out[4]: array([1, 2, 3, 6, 7, 8])

Note that the code above works indeed if a and b are lists instead of numpy arrays. The output I want:

Out[4]: array([[1, 2, 3], [6, 7, 8]])

EDIT

vstack works indeed for a and b as in above. It does not in my real life case, where I want to iteratively fill an empty array with vectors of some dimension.

hist=[]
for i in range(len(filenames)):
    fileload = np.load(filenames[i])
    maxarray.append(fileload['maxamp'])

    hist_t, bins_t = np.histogram(maxarray[i], bins=np.arange(0,4097,4))
    hist = np.vstack((hist,hist_t))

SOLUTION:

I found the solution: you have to properly initialize the array e.g.: How to add a new row to an empty numpy array

deppep
  • 135
  • 1
  • 1
  • 7

1 Answers1

1

For np.concatenate to work here the input arrays should have two dimensions, as you wasnt a concatenation along the second axis here, and the input arrays only have 1 dimension.

You can use np.vstack here, which as explained in the docs:

It is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N)

a = np.array([1, 2, 3])
b = np.array([6, 7, 8])

np.vstack([a, b])

array([[1, 2, 3],
       [6, 7, 8]])
yatu
  • 86,083
  • 12
  • 84
  • 139
  • This does work indeed for a and b as above. But it does not in my real life case: i have an empty array which i want to fill iterativelt with arrays of the same dimensions. I'll edit OP in a moment. – deppep Jul 23 '19 at 10:50
  • 1
    @deppep growing an array iteratively is a bad idea anyway. Arrays, unlike lists, are not designed to be resized; doing so involves a full reallocation + copy, so an iterative scheme will have quadratic complexity (lists: linear). – Paul Panzer Jul 23 '19 at 11:03