0
votes

See some examples

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate((a,b), axis=0)) # [1,2,3,4,5,6]
print(np.hstack((a,b))) # [1,2,3,4,5,6]

print(np.vstack((a,b))) # [[1,2,3],[4,5,6]]
print(np.concatenate((a,b), axis=1)) # IndexError: axis 1 out of bounds [0, 1)

The result of hstack is the same as concatenate along axis=0, but the api document says hstack=concatenate along axis=1, please look at the https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.hstack.html#numpy.hstack

And concatenating along the axis=1 raise an IndexError, the api document says hstack=concatenate along axis=0, please look at the https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.vstack.html#numpy.vstack

Can anybody explain it?By the way, can anybody explain how to broadcast when the ndarray's dimension is less than 2 and concatenating along axis=1?

2

2 Answers

0
votes

Look at the actual code for hstack:

arrs = [atleast_1d(_m) for _m in tup]
# As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
if arrs[0].ndim == 1:
    return _nx.concatenate(arrs, 0)
else:
    return _nx.concatenate(arrs, 1)

I don't see anything in the docs about axis=1. The term it uses is 'stack them horizontally'.

As I noted a year ago, Concatenation of 2 1D numpy arrays along 2nd axis, earlier versions don't raise an error if the axis is too high. But in 1.12 we get an error.

There is a newish np.stack that can add a dimension where needed:

In [46]: np.stack((np.arange(3), np.arange(4,7)),axis=1)
Out[46]: 
array([[0, 4],
       [1, 5],
       [2, 6]])

The base function is concatenate. The various stack functions adjust array dimensions in one way or other, and then do concatenate. Look at their code to see the details. (I've summarized the differences in earlier posts as well).

0
votes

np.hstack(tup) and np.concatenate(tup, axis=1) are indeed equivalent but only if tup contains arrays that are at least 2-dimensional. This was in fact spelled out in the documentation for vstack, so it looks like it was just an oversight that it did not also in the documentation for hstack; it will for future versions though.