Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Concatenating column vectors using numpy arrays

I'd like to concatenate 'column' vectors using numpy arrays but because numpy sees all arrays as row vectors by default, np.hstack and np.concatenate along any axis don't help (and neither did np.transpose as expected).

a = np.array((0, 1))
b = np.array((2, 1))
c = np.array((-1, -1))

np.hstack((a, b, c))
# array([ 0,  1,  2,  1, -1, -1])  ## Noooooo
np.reshape(np.hstack((a, b, c)), (2, 3))
# array([[ 0,  1,  2], [ 1, -1, -1]]) ## Reshaping won't help

One possibility (but too cumbersome) is

np.hstack((a[:, np.newaxis], b[:, np.newaxis], c[:, np.newaxis]))
# array([[ 0,  2, -1], [ 1,  1, -1]]) ##

Are there better ways?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I believe numpy.column_stack should do what you want. Example:

>>> a = np.array((0, 1))
>>> b = np.array((2, 1))
>>> c = np.array((-1, -1))
>>> numpy.column_stack((a,b,c))
array([[ 0,  2, -1],
       [ 1,  1, -1]])

It is essentially equal to

>>> numpy.vstack((a,b,c)).T

though. As it says in the documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...