计算 pandas 数据框中列值之间的距离

Calculating distance between column values in pandas dataframe

我附上了我的数据集样本。我对 Panda 的经验很少,因此,我很难提出问题。

我想要做的是根据州和县为每个索引填充 'dist' 列(笛卡尔坐标:p1 = (lat1,long1) ; p2 = (lat2,long2))。

每个县可能有多个 p1。我们在计算距离时使用最接近 p2 的那个。当一个县没有 p1 值时,我们只需使用序列中的下一个值。

如何简洁地设置这个问题?我可以想象 运行 是 county/state 上的迭代器,但无法超越它。

[编辑] 这是下面建议的数据帧头。 (忽略图片中的不匹配)

   lat1 long1 state           county   lat2  long2
0     .     .    AK   Aleutians West   11.0   23.0
1     .     .    AK     Wade Hampton   33.0   11.0
2     .     .    AK      North Slope   55.0   11.0
3     .     .    AK  Kenai Peninsula   44.0   11.0
4     .     .    AK        Anchorage   11.0   11.0
5     1     2    AK        Anchorage    NaN    NaN
6     .     .    AK        Anchorage   55.0   44.0
7     3     4    AK        Anchorage    NaN    NaN
8     .     .    AK        Anchorage    3.0    2.0
9     .     .    AK        Anchorage    5.0   11.0
10    .     .    AK        Anchorage   42.0   22.0
11    .     .    AK        Anchorage   11.0    2.0
12    .     .    AK        Anchorage  444.0    1.0
13    .     .    AK        Anchorage    1.0    2.0
14    0     2    AK        Anchorage    NaN    NaN
15    .     .    AK        Anchorage    1.0    1.0
16    .     .    AK        Anchorage  111.0   11.0

下面是我将如何使用 Shapely,底层引擎 Geopandas,我将使用随机数据。

from shapely.geometry import LineString
import pandas as pd
import random


def gen_random():
  return [random.randint(1, 100) for x in range(20)]

j = {"x1": gen_random(), "y1": gen_random(),
     "x2": gen_random(), "y2": gen_random(),}
df = pd.DataFrame(j)


def get_distance(k):
  lstr = LineString([(k.x1, k.y1,), (k.x2, k.y2) ])
  return lstr.length

df["Dist"] = df.apply(get_distance, axis=1)

身材匀称:http://toblerity.org/shapely/manual.html#introduction 大熊猫:http://geopandas.org/