【发布时间】:2017-04-23 22:14:22
【问题描述】:
示例 CSV 如下所示:
user_id lat lon
1 19.111841 72.910729
1 19.111342 72.908387
2 19.111542 72.907387
2 19.137815 72.914085
2 19.119677 72.905081
2 19.129677 72.905081
3 19.319677 72.905081
3 19.120217 72.907121
4 19.420217 72.807121
4 19.520217 73.307121
5 19.319677 72.905081
5 19.419677 72.805081
5 19.629677 72.705081
5 19.111860 72.911347
5 19.111860 72.931346
5 19.219677 72.605081
6 19.319677 72.805082
6 19.419677 72.905086
我知道我可以使用 haversine 进行距离计算(并且 python 也有 hasrsine 包):
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees).
Source: http://gis.stackexchange.com/a/56589/15183
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
km = 6371 * c
return km
但是,我只想计算 same id 内的距离。 所以预期的答案是这样的:
user_id lat lon result
1 19.111841 72.910729 NaN
1 19.111342 72.908387 xx*
2 19.111542 72.907387 NaN
2 19.137815 72.914085 xx
2 19.119677 72.905081 xx
2 19.129677 72.905081 xx
3 19.319677 72.905081 NaN
3 19.120217 72.907121 xx
4 19.420217 72.807121 NaN
4 19.520217 73.307121 xx
5 19.319677 72.905081 NaN
5 19.419677 72.805081 xx
5 19.629677 72.705081 xx
5 19.111860 72.911347 xx
5 19.111860 72.931346 xx
5 19.219677 72.605081 xx
6 19.319677 72.805082 NaN
6 19.419677 72.905086 xx
*: xx 是以公里为单位的距离数字。
我该怎么做?
【问题讨论】:
-
为什么有 4 个条目的 id 相同但值重复?你如何计算 4 个条目之间的距离?
-
您已经知道如何获取距离,您的问题似乎更多是关于对您的数据进行 group 的热点。这是正确的吗?
-
您应该更改问题的标题,因为它与距离计算无关。此外,@EyuelDK 提出的问题仍未得到答复。您有两个以上具有相同 ID 的元素,您希望如何获得所有元素的距离?在所有可能的组合之间?相邻元素之间?
-
@Gabriel,你为什么要删除
pandas标签? -
不,但我希望用
python标记的问题在某种程度上与它相关。这个问题显然与csv相关,而它与pandas完全无关(除了在此处未发布的一些代码中显然使用pandas的OP)我不会删除haversine标签,但是它与pandas标签一样无关紧要。我想如果你mus在这里没有pandas,那就这样吧。干杯。
标签: python csv pandas gis distance