如果一个数据帧中的2D点与另一数据帧中2D点之间的欧几里得最小,则将它们替换为2D点



我有一个数据帧df1,其中两列V1和V2表示一个点的两个坐标。

df1

V1          V2
1.30344679  0.060199021
1.256628917 0.095897457
0.954959945 0.237514922
1.240081297 0.053228255
1.35765432  0.033412217
1.228539425 0.079924064
1.080489363 0.204162117
1.27587021  0.085286683
1.44        0
0.93719247  0.310292371

还有另一个数据帧df2,其中两列C1和C2表示一个点的两个坐标。

df2

C1          C2
0.083       0.323657888
1.293934451 0.046950426
1.252872503 0.09000528
0.148131303 0.347930828

df1和df2具有不同的长度。在本例中,将替换df1中的四个点。从本质上讲,如果df2中的四个点之间的欧几里得最小,那么它们将替换df1中的四点。

我们也可以说,df2中的每个点只替换df1中最接近的点。我们如何才能做到这一点?

重复问题:小数点后的位数为9。因此,我假设不会出现重复的问题(即,df1中的多个点具有相同的欧几里得距离,并且距离值最低(。如果出现这种情况,我们可以随机替换其中任何一行?

所需输出:修正df1的长度与df1相同,但修正df1替换了df2的四个点。

这里有一个以列表形式处理数据的解决方案。修改它以使用数据帧是留给读者的练习。老实说,由于这需要一行一行地完成,所以最好将列作为列表取出,稍后再将其转换回来。

注意,正如我在上面试图暗示的那样,这并不能保证";最佳";解决方案对于df2中的每个点,我们选择df1中尚未被替换的最近点。另一种选择很可能会减少TOTAL错误。

import math
df1 = [
[1.30344679 ,  0.060199021],
[1.256628917,  0.095897457],
[0.954959945,  0.237514922],
[1.240081297,  0.053228255],
[1.35765432 ,  0.033412217],
[1.228539425,  0.079924064],
[1.080489363,  0.204162117],
[1.27587021 ,  0.085286683],
[1.44       ,  0],
[0.93719247 ,  0.310292371]
]
df2 = [
[0.083      ,  0.323657888],
[1.293934451,  0.046950426],
[1.252872503,  0.09000528],
[0.148131303,  0.347930828]
]
def printer(d):
for row in d:
print( "%.9f %.9f" % tuple(row) )
def dist(p1,p2):
return math.sqrt( (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 )
# For each point in df2:
print("Before")
printer(df1)
replaced = set()
for p2 in df2:
# Compute the distance to each point in df1.
distances = [(dist(p1,p2), i1) for (i1,p1) in enumerate(df1)]
# Sort them by distance.
distances.sort()
# Pick the closest that has not already been replaced.
top = distances.pop(0)
while top[1] in replaced:
top = distances.pop(0)
# Replace it.
df1[top[1]] = p2
replaced.add( top[1] )
print("After")
printer(df1)

输出:

Before
1.303446790 0.060199021
1.256628917 0.095897457
0.954959945 0.237514922
1.240081297 0.053228255
1.357654320 0.033412217
1.228539425 0.079924064
1.080489363 0.204162117
1.275870210 0.085286683
1.440000000 0.000000000
0.937192470 0.310292371
After
1.293934451 0.046950426
1.252872503 0.090005280
0.148131303 0.347930828
1.240081297 0.053228255
1.357654320 0.033412217
1.228539425 0.079924064
1.080489363 0.204162117
1.275870210 0.085286683
1.440000000 0.000000000
0.083000000 0.323657888

最新更新