Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

python - When should I use hstack/vstack vs append vs concatenate vs column_stack?

Simple question: what is the advantage of each of these methods. It seems that given the right parameters (and ndarray shapes) they all work seemingly equivalently. Do some work in place? Have better performance? Which functions should I use when?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All the functions are written in Python except np.concatenate. With an IPython shell you just use ??.

If not, here's a summary of their code:

vstack
concatenate([atleast_2d(_m) for _m in tup], 0)
i.e. turn all inputs in to 2d (or more) and concatenate on first

hstack
concatenate([atleast_1d(_m) for _m in tup], axis=<0 or 1>)

colstack
transform arrays with (if needed)
    array(arr, copy=False, subok=True, ndmin=2).T

append
concatenate((asarray(arr), values), axis=axis)

In other words, they all work by tweaking the dimensions of the input arrays, and then concatenating on the right axis. They are just convenience functions.


And newer np.stack:

arrays = [asanyarray(arr) for arr in arrays]
shapes = set(arr.shape for arr in arrays)
result_ndim = arrays[0].ndim + 1
axis = normalize_axis_index(axis, result_ndim)
sl = (slice(None),) * axis + (_nx.newaxis,)

expanded_arrays = [arr[sl] for arr in arrays]
concatenate(expanded_arrays, axis=axis, out=out)

That is, it expands the dims of all inputs (a bit like np.expand_dims), and then concatenates. With axis=0, the effect is the same as np.array.

hstack documentation now adds:

The functions concatenate, stack and block provide more general stacking and concatenation operations.

np.block is also new. It, in effect, recursively concatenates along the nested lists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...