【发布时间】:2018-05-01 00:56:23
【问题描述】:
如果给定"starting_point"和"list_of_points",我们如何创建一个新的numpy数组“distances”,其中包含“starting_point”和“list_of_points”中每个点之间的距离?
我尝试通过使用以下代码循环 "list_of_points" 来做到这一点,但它不起作用:
distances = sqrt( (list_of_points[num][0] - starting_point[0])^2 + list_of_points[num][1] - starting_point[1])^2 ) for num in range (0,4)
starting_point = np.array([1.0, 2.0])
list_of_points = np.array([-5.0, -3.0], [-4.0, 2.0], [7.0, 8.0], [6.0, -9.0])
distances = np.array([ d1 ], [ d2 ], [ d3 ], [ d4 ])
【问题讨论】:
-
你的代码的第一个问题是你的括号不平衡,所以整个事情是一个 SyntaxError。第二个问题是
^2不是均方,而是异或2;你想要**2。您的第三个问题是list_of_points不是有效的数组构造函数。 -
无论如何,你很少想在 numpy 中循环;这违背了使用它的全部目的。你可能想要
sqrt((list_of_points[:,0] - starting_point[0])** 2 + (list_of_points[:,1] - starting_point[1])**2)之类的东西。或者,更好的是,查找np.hypot或np.linalg.norm、scipy.spatial.distance等。 -
如果不使用循环,如何遍历所有“list_of_points”来创建“距离”?
-
numpy 的全部意义在于它的所有操作都是元素级的。您只需执行
list_of_points[:,0] - starting_point[0],它就会返回一个包含所有差异的数组。如果你不明白,你需要在继续之前阅读基本的 numpy 教程。 -
你也可以使用einsum,它非常灵活。有很多例子……例如stackoverflow.com/questions/46571624/…