是否有一种numpy-thonic方式,例如函数,来查找数组中最接近的值?
例:
np.find_nearest( array, value )
Run Code Online (Sandbox Code Playgroud) 问题
想象一下,我站在机场.给定地理坐标对,如何有效地确定我所在的机场?
输入
(x,y)
代表我所站的位置.[(a1,b1), (a2,b2)...]
,其中每个坐标对代表一个机场.期望的输出
坐标对(a,b)
从该组机场坐标表示最近的机场的点对(x,y)
.
低效的解决方案
这是我解决这个问题的低效尝试.它在机场组的长度上显然是线性的.
shortest_distance = None
shortest_distance_coordinates = None
point = (50.776435, -0.146834)
for airport in airports:
distance = compute_distance(point, airport)
if distance < shortest_distance or shortest_distance is None:
shortest_distance = distance
shortest_distance_coordinates = airport
Run Code Online (Sandbox Code Playgroud)
问题
如何改进这个解决方案?这可能涉及的预过滤基于我们目前站在位置的坐标机场的名单,或者按照一定的顺序排序事前他们一些方法.
我有一个具有不规则间隔纬度和经度坐标的 xarray 数据集。我的目标是在最接近某个纬度/经度的点处找到变量的值。
由于x
和y
尺寸不是纬度/经度值,因此ds.sel()
在这种情况下似乎不能单独使用该方法。是否有一种以 xarray 为中心的方法来通过参考多维纬度/经度维度来定位最接近所需纬度/经度的点?例如,我想提取最接近lat=21.2
和的 SPEED 值lon=-122.68
。
下面是一个示例数据集...
lats = np.array([[21.138 , 21.14499, 21.15197, 21.15894, 21.16591],
[21.16287, 21.16986, 21.17684, 21.18382, 21.19079],
[21.18775, 21.19474, 21.20172, 21.2087 , 21.21568],
[21.21262, 21.21962, 21.22661, 21.23359, 21.24056],
[21.2375 , 21.2445 , 21.25149, 21.25848, 21.26545]])
lons = np.array([[-122.72 , -122.69333, -122.66666, -122.63999, -122.61331],
[-122.7275 , -122.70082, -122.67415, -122.64746, -122.62078],
[-122.735 , -122.70832, -122.68163, -122.65494, -122.62825],
[-122.7425 , -122.71582, -122.68912, -122.66243, -122.63573],
[-122.75001, -122.72332, -122.69662, -122.66992, …
Run Code Online (Sandbox Code Playgroud) 我有一个dict
需要整数键的:
a = {}
a[1] = 100
a[55] = 101
a[127] = 102
Run Code Online (Sandbox Code Playgroud)
我希望在询问时能够选择最近的邻居:
a[20] # should return a[1] = 100
a[58] # should return a[55] = 101
a[167] # should return a[127] = 102
Run Code Online (Sandbox Code Playgroud)
有没有一种Python式的方法可以做到这一点?(我想这可以通过循环所有字典来完成,但这可能不是最优雅的解决方案?)
双索引(也是整数)同样的问题:
b[90, 1] = 100, b[90, 55] = 101, b[90, 127] = 102
b[70, 1] = 40, b[70, 45] = 41, b[70, 107] = 42
Run Code Online (Sandbox Code Playgroud)
我希望能够得到 b[73, 40] = b[70, 45] = 41
,即二维平面中的最近邻。
I have a np array, X that is size 1000 x 1000 where each element is a real number. I want to find the 5 closest points for every point in each row of this np array. Here the distance metric can just be abs(x-y). I have tried to do
for i in range(X.shape[0]):
knn = NearestNeighbors(n_neighbors=5)
knn.fit(X[i])
for j in range(X.shape[1])
d = knn.kneighbors(X[i,j], return_distance=False)
Run Code Online (Sandbox Code Playgroud)
However, this does not work for me and I am not sure how efficient …
我有这个带有点的numpy数组,类似于
[(x1,y1), (x2,y2), (x3,y3), (x4,y4), (x5,y5)]
Run Code Online (Sandbox Code Playgroud)
我想做的是获得所有最小距离的数组.所以对于第1点(x1, y1)
,我想要最接近它的点的距离,对于点2来说是相同的(x2,y2)
......距离是sqrt((x1-x2)^2 + (y1-y2)^2)
.
这显然是一个与我的数组相同长度的数组(在这种情况下:5个点 - > 5个最小距离).
任何简洁的方法,而不诉诸循环?