我有这个函数返回一个numpy
数组,其中包含分别代表x
和y
坐标的两个向量,我想把它们变成(x; y)对。 / p>
例如:
import numpy as np
def rotate(coords, angle, center=(0, 0,)):
rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
return rotated
xy = np.array([[1,2],[3,4],[5,6],[6,7]])
a = rotate(xy,20)
print a
这给了我:
[[ 0.25565233 1.45099729 2.64634224 3.24401472]
[ 2.22140538 4.78483091 7.34825644 8.62996921]]
但是,我实际上想要这个输出:
[[0.25565233, 2.22140538]
[1.45099729, 4.78483091]
[2.64634224, 7.34825644]
[3.24401472, 8.62996921]]
答案 0 :(得分:3)
只需转置。您可以使用numpy.transpose
,也可以使用重载运算符.T
:
xy = np.array([[1,2],[3,4],[5,6],[6,7]]);
a = rotate(xy,20).T # <--- Modification here
这样做会给出:
>>> print a
[[ 0.25565233 2.22140538]
[ 1.45099729 4.78483091]
[ 2.64634224 7.34825644]
[ 3.24401472 8.62996921]]
如果您想避免转置输出,可以让该功能执行此操作。只需转置rotate
函数中返回的内容:
def rotate(coords, angle, center=(0, 0,)):
rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
return rotated.T #<-- Modification here
因此,您可以在不进一步思考的情况下做您以前做过的事情:
xy = np.array([[1,2],[3,4],[5,6],[6,7]]);
a = rotate(xy,20)
......这给了我们:
>>> print a
[[ 0.25565233 2.22140538]
[ 1.45099729 4.78483091]
[ 2.64634224 7.34825644]
[ 3.24401472 8.62996921]]
答案 1 :(得分:1)
你想要transpose它 -
In [3]: n = np.array([[ 0.25565233, 1.45099729, 2.64634224 , 3.24401472],
...: [ 2.22140538 , 4.78483091 , 7.34825644 , 8.62996921]])
In [4]: n
Out[4]:
array([[ 0.25565233, 1.45099729, 2.64634224, 3.24401472],
[ 2.22140538, 4.78483091, 7.34825644, 8.62996921]])
In [6]: n.T
Out[6]:
array([[ 0.25565233, 2.22140538],
[ 1.45099729, 4.78483091],
[ 2.64634224, 7.34825644],
[ 3.24401472, 8.62996921]])
在你的情况下 -
def rotate(coords, angle, center=(0, 0,)):
rotated = np.array([np.cos(np.radians(angle)) * (coords[:,0] - center[0]) - np.sin(np.radians(angle)) * (coords[:,1] - center[1]) + center[0],
np.sin(np.radians(angle)) * (coords[:,0] - center[0]) + np.cos(np.radians(angle)) * (coords[:,1] - center[1]) + center[1]])
return rotated
xy = np.array([[1,2],[3,4],[5,6],[6,7]])
a = rotate(xy,20)
print a.T
>> [[ 0.25565233 2.22140538]
[ 1.45099729 4.78483091]
[ 2.64634224 7.34825644]
[ 3.24401472 8.62996921]]