python - Pandas 数据框连续行之间的重复计算

标签 python pandas numpy dataframe gps

我想计算沿 GPS 坐标路径的距离,这些坐标存储在数据框中的两列中。

import pandas as pd

df = pd.DataFrame({ 'lat' : [1, 2.5, 3, 1.2],
                    'lng' : [1, 1, 2.1, 1],
                    'label': ['foo', 'bar', 'zip', 'foo']})
print df

输出

  label  lat  lng
0   foo  1.0  1.0
1   bar  2.5  1.0
2   zip  3.0  2.1
3   foo  1.2  1.0

GPS 坐标以弧度存储。因此,数据框第一行和第二行之间的距离可以计算如下:

import math as m

r1 = 0
r2 = 1

distance =m.acos(m.sin(df.lat[r1]) * m.sin(df.lat[r2]) + 
     m.cos(df.lat[r1]) * m.cos(df.lat[r2]) * m.cos(df.lng[r2]-df.lng[r1]))*6371

我想在每对连续行之间重复此计算,然后将每个短距离添加到完整路径的较长最终距离中。

我可以将它放入数据帧的 n-1 行的循环中,但是是否有更 pythonic 的方法来做到这一点?

最佳答案

矢量化 Haversine 函数:

def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
    """
    slightly modified version: of http://stackoverflow.com/a/29546836/2901002

    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees or in radians)

    All (lat, lon) coordinates must have numeric dtypes and be of equal length.

    """
    if to_radians:
        lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])

    a = np.sin((lat2-lat1)/2.0)**2 + \
        np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2

    return earth_radius * 2 * np.arcsin(np.sqrt(a))

解决方法:

df['dist'] = haversine(df['lat'], df['lng'],
                       df['lat'].shift(), df['lng'].shift(),
                       to_radians=False)

结果:

In [65]: df
Out[65]:
  label  lat  lng          dist
0   foo  1.0  1.0           NaN
1   bar  2.5  1.0   9556.500000
2   zip  3.0  2.1   7074.983158
3   foo  1.2  1.0  10206.286067

关于python - Pandas 数据框连续行之间的重复计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450530/

相关文章:

python - 计算大于当前行值但小于其他列值的连续行数

numpy - 当所有值为 NaN 和字符串时 nanpercentile 出现错误

python - 将多个数组与 numpy 数组相交的最佳方法是什么?

python - 如何分块循环遍历 Python 中的二进制文件

python 和 symbian - 击键捕获

python - Pandas 。转换表结构

python - 将矩阵中位置低于 0 的所有元素转换为 0 (Python)

python - 通过在 Python 中使用 Paramiko 模块,我如何在 Linux 服务器上编辑文件?

python - App Engine Dev Server 数据存储更新速度不够快?

python - 更改列表中列的大小写