Concatenating two one-dimensional NumPy arrays Concatenating two one-dimensional NumPy arrays python python

Concatenating two one-dimensional NumPy arrays


The line should be:

numpy.concatenate([a,b])

The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.

From the NumPy documentation:

numpy.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays together.

It was trying to interpret your b as the axis parameter, which is why it complained it couldn't convert it into a scalar.


There are several possibilities for concatenating 1D arrays, e.g.,

numpy.r_[a, a],numpy.stack([a, a]).reshape(-1),numpy.hstack([a, a]),numpy.concatenate([a, a])

All those options are equally fast for large arrays; for small ones, concatenate has a slight edge:

enter image description here

The plot was created with perfplot:

import numpyimport perfplotperfplot.show(    setup=lambda n: numpy.random.rand(n),    kernels=[        lambda a: numpy.r_[a, a],        lambda a: numpy.stack([a, a]).reshape(-1),        lambda a: numpy.hstack([a, a]),        lambda a: numpy.concatenate([a, a]),    ],    labels=["r_", "stack+reshape", "hstack", "concatenate"],    n_range=[2 ** k for k in range(19)],    xlabel="len(a)",)


The first parameter to concatenate should itself be a sequence of arrays to concatenate:

numpy.concatenate((a,b)) # Note the extra parentheses.


matomo