所以,继续我和 @TheBlackCat 的讨论这个答案,我想知道将参数传递给 Numpy 向量化函数的最佳方法。所讨论的函数定义如下:
vect_dist_funct = np.vectorize(lambda p1, p2: vincenty(p1, p2).meters)
where, vincenty
来自地质学包.
我目前打电话vect_dist_funct
以这种方式:
def pointer(point, centroid, tree_idx):
intersect = list(tree_idx.intersection(point))
if len(intersect) > 0:
points = pd.Series([point]*len(intersect)).values
polygons = centroid.loc[intersect].values
dist = vect_dist_funct(points, polygons)
return pd.Series(dist, index=intercept, name='Dist').sort_values()
else:
return pd.Series(np.nan, index=[0], name='Dist')
points['geometry'].apply(lambda x: pointer(point=x.coords[0], centroid=line['centroid'], tree_idx=tree_idx))
(请参考这里的问题:带标签的数据类型 Python)
我的问题与函数内部发生的情况有关pointer
。我转变的原因points
to a pandas.Series
然后获取值(在第四行,就在if
声明)是使其形状与多边形相同。如果我只是将点称为points = [point]*len(intersect)
or as points = itertools.repeat(point, len(intersect))
,Numpy 抱怨它“不能一起广播大小为 (n,2) 和大小 (n,) 的数组”(n 是intersect
).
如果我打电话vect_dist_funct
像这样:dist = vect_dist_funct(itertools.repeat(points, len(intersect)), polygons)
, vincenty
抱怨我给它传递了太多的参数。我完全不明白两者之间的区别。
请注意,这些是坐标,因此总是成对的。以下是如何操作的示例point
and polygons
看起来像:
point = (-104.950752 39.854744) # Passed directly to the function like this.
polygons = array([(-104.21750802451864, 37.84052458697633),
(-105.01017084789603, 39.82012158954065),
(-105.03965315742742, 40.669867471420886),
(-104.90353460825702, 39.837631505433706),
(-104.8650601872832, 39.870796282334744)], dtype=object)
# As returned by statement centroid.loc[intersect].values
最好的通话方式是什么vect_dist_funct
在这种情况下,这样我就可以进行矢量化调用,并且 Numpy 和 vincenty 都不会抱怨我传递了错误的参数?此外,还寻求能够最小化存储器消耗并提高速度的技术。目标是计算点到每个多边形质心之间的距离。