2016-09-26 79 views
-2

我还是python的新手。我需要帮助来计算折线的长度与简单的距离计算:从csv计算多段线的长度

distance = sqrt((x1 - x2)**2 + (y1 - y2)**2) 

比如我输入CSV看起来是这样的。

id x  y  sequence 
1 1.5 2.5  0 
1 3.2 4.9  1 
1 3.6 6.6  2 
1 4.4 5.0  3 
2 2.0 4.5  0 
2 3.5 6.0  1 

我有'id'和'sequence'(线顶点的序号)。如何读取csv文件?如果当前'id'与前一行'id'具有相同的值,则执行距离计算:sqrt((x [i] - x [i-1])** 2 +(y [i] - y [i -1])** 2)。之后,按'id'分组并计算其“距离”值。

输出CSV应该是这样的:

id distance 
1  ? 
2  ? 

在此先感谢。

+2

这是怎么样的问题通常会被关闭。如果你解释什么不工作或者你不知道如何一次完成1个问题,你更可能得到有用的回答。 – m0s

+2

函数的参数列表有两个名为y2而没有名为y1的参数。 – barny

回答

1

折线:

enter image description here

两个点一个点和折线之间的距离之间的距离:

def lineMagnitude (x1, y1, x2, y2): 
    lineMagnitude = math.sqrt(math.pow((x2 - x1), 2)+ math.pow((y2 - y1), 2)) 
    return lineMagnitude 

#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline). 
def DistancePointLine (px, py, x1, y1, x2, y2): 
    #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba 
    LineMag = lineMagnitude(x1, y1, x2, y2) 

    if LineMag < 0.00000001: 
     DistancePointLine = 9999 
     return DistancePointLine 

    u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1))) 
    u = u1/(LineMag * LineMag) 

    if (u < 0.00001) or (u > 1): 
     #// closest point does not fall within the line segment, take the shorter distance 
     #// to an endpoint 
     ix = lineMagnitude(px, py, x1, y1) 
     iy = lineMagnitude(px, py, x2, y2) 
     if ix > iy: 
      DistancePointLine = iy 
     else: 
      DistancePointLine = ix 
    else: 
     # Intersecting point is on the line, use the formula 
     ix = x1 + u * (x2 - x1) 
     iy = y1 + u * (y2 - y1) 
     DistancePointLine = lineMagnitude(px, py, ix, iy) 

    return DistancePointLine 

欲了解更多信息,请访问:http://www.maprantala.com/2010/05/16/measuring-distance-from-a-point-to-a-line-segment/