【发布时间】:2020-06-02 22:57:14
【问题描述】:
我有以下几点:
import numpy as np
points = np.array([[49.8, 66.35],
[49.79, 66.35],
[49.79, 66.35],
[44.65, 67.25],
[44.65, 67.25],
[44.65, 67.25],
[44.48, 67.24],
[44.63, 67.21],
[44.68, 67.2],
[49.69, 66.21],
[49.85, 66.17],
[50.51, 66.04],
[49.8, 66.35]])
当我绘制它们时,我得到了这个形状:
import matplotlib.pyplot as plt
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)
从点列表中可以看出,其中一些是多余的(即查看点 1 和 2(从 0 开始))。
为了只保留非冗余点,我回复了这个问题的答案: Removing duplicate columns and rows from a NumPy 2D array
def unique_2D(a):
order = np.lexsort(a.T)
a = a[order]
diff = np.diff(a, axis=0)
ui = np.ones(len(a), 'bool')
ui[1:] = (diff != 0).any(axis=1)
return a[ui]
我将这个函数应用到我的积分上,我得到:
non_redundant_points = unique_2D(points)
这是打印的保留点列表:
[[ 50.51 66.04]
[ 49.85 66.17]
[ 49.69 66.21]
[ 49.79 66.35]
[ 49.8 66.35]
[ 44.68 67.2 ]
[ 44.63 67.21]
[ 44.48 67.24]
[ 44.65 67.25]]
但是,现在我面临以下问题:当我绘制它们时,订单不知何故没有保留......
x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)
你知道我该如何解决这个问题吗?
为了方便复制和粘贴,这里是完整的代码:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([[49.8, 66.35],
[49.79, 66.35],
[49.79, 66.35],
[44.65, 67.25],
[44.65, 67.25],
[44.65, 67.25],
[44.48, 67.24],
[44.63, 67.21],
[44.68, 67.2],
[49.69, 66.21],
[49.85, 66.17],
[50.51, 66.04],
[49.8, 66.35]])
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)
def unique_2D(a):
order = np.lexsort(a.T)
a = a[order]
diff = np.diff(a, axis=0)
ui = np.ones(len(a), 'bool')
ui[1:] = (diff != 0).any(axis=1)
return a[ui]
x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)
【问题讨论】:
-
为什么不简单地遍历点,如果一个点与前一个相同,跳过它?
-
假设最后一个坐标是 [49.79, 66.35] 而不是 [49.80, 66.35];你想摆脱它,因为它以前出现过吗?还是您只想保留相邻的相同值?我们需要担心浮点精度吗?如果其中一个数字是 [49.79000001, 66.34999998],是否算作 [49.79, 66.35] 的重复?
标签: python list numpy matplotlib