【问题标题】:How to add random points in between the given points?如何在给定点之间添加随机点?
【发布时间】:2020-05-04 06:29:18
【问题描述】:
我有数据点作为数据框,就像在图 1 中表示的那样
样本数据
df=
74 34
74.5 34.5
75 34.5
75 34
74.5 34
74 34.5
76 34
76 34.5
74.5 34
74 34.5
75.5 34.5
75.5 34
75 34
75 34.5
我想在这些点之间添加随机点,但保持初始点的形状。
所需的输出将类似于图 2(黑点代表随机点。红线代表边界)
~有什么建议吗?我正在寻找一个通用的解决方案,因为外边界的几何形状会在问题中发生变化
【问题讨论】:
标签:
python
pandas
numpy
scatter
【解决方案1】:
如果形状是凸的,那就很简单了:
def get_random_point(points):
point_selectors = np.random.randint(0, len(points), 2)
scale = np.random.rand()#value between 0 and 1
start_point = points[point_selectors[0]]
end_point = points[point_selectors[1]]
return start_point + (end_point - start_point) * scale
您指定的形状不是凸的。但是,如果您没有另外指定哪些点构成了形状的外部或其他约束,例如您只想让线平行于 x 或 y 轴,您看到的形状在数学上没有充分指定。
最后一点:有一些算法可以检查一个点是否在多边形内(Point in polygon)。
然后,您可以 1) 指定边界多边形 2) 在形状的边界矩形内生成一个点,以及 3) 测试该点是否位于多边形的形状内。
【解决方案2】:
插值可能值得研究:
import numpy as np
# lets suppose y = 2x and x[i], y[i] is a data point
x = [1, 5, 16, 20, 60]
y = [2, 10, 32, 40, 120]
interp_here = [7, 8, 9, 21] # the points where we are going to interpolate values.
print(np.interp(interp_here, x, y)) ## [14. 16. 18. 42.]
如果您想要随机点,那么您可以使用上述作为指导线,然后为每个点添加/减去一些增量。