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
436 views
in Technique[技术] by (71.8m points)

python - Numpy Vector (N,1) dimension -> (N,) dimension conversion

I have a question regarding the conversion between (N,) dimension arrays and (N,1) dimension arrays. For example, y is (2,) dimension.

A=np.array([[1,2],[3,4]])

x=np.array([1,2])

y=np.dot(A,x)

y.shape
Out[6]: (2,)

But the following will show y2 to be (2,1) dimension.

x2=x[:,np.newaxis]

y2=np.dot(A,x2)

y2.shape
Out[14]: (2, 1)

What would be the most efficient way of converting y2 back to y without copying?

Thanks, Tom

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

reshape works for this

a  = np.arange(3)        # a.shape  = (3,)
b  = a.reshape((3,1))    # b.shape  = (3,1)
b2 = a.reshape((-1,1))   # b2.shape = (3,1)
c  = b.reshape((3,))     # c.shape  = (3,)
c2 = b.reshape((-1,))    # c2.shape = (3,)

note also that reshape doesn't copy the data unless it needs to for the new shape (which it doesn't need to do here):

a.__array_interface__['data']   # (22356720, False)
b.__array_interface__['data']   # (22356720, False)
c.__array_interface__['data']   # (22356720, False)

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

...