Pandas - 使用 itertuples 创建列

Wal*_*eed 6 python loops list python-itertools pandas

我有一个pandas.DataFrame和。我还有一个坐标列表。我正在尝试计算纬度和经度与列表中每个坐标对之间的距离(使用半正弦公式)。然后我想返回最小距离,并在数据框中使用该值创建一个新列。AcctIdLatitudeLongitude

但是,我的输出表仅返回循环中最后一行的距离值。我尝试过使用itertuplesiterrows和普通循环,但没有一种方法对我来说非常有效。

df
AcctId   Latitude   Longitude
123      40.50      -90.13
123      40.53      -90.21
123      40.56      -90.45
123      40.63      -91.34

coords = [41.45,-95.13,39.53,-100.42,45.53,-95.32]

for row in df.itertuples():
    Latitude = row[1]
    Longitude = row[2]
    distances = []
    lat = []
    lng = []
    for i in xrange(0, len(coords),2):
          distances.append(haversine_formula(Latitude,coords[i],Longitude,coords[i+1])
          lat.append(coords[i])
          lng.append(coords[i+1])
          min_distance = min(distances)
    df['Output'] = min_distance
Run Code Online (Sandbox Code Playgroud)

期望的输出:

df
AcctId   Latitude    Longitude    Output
123      40.50      -90.13         23.21
123      40.53      -90.21         38.42
123      40.56      -90.45         41.49
123      40.63      -91.34         42.45
Run Code Online (Sandbox Code Playgroud)

实际输出:

df
AcctId   Latitude    Longitude    Output
123      40.50      -90.13         42.45
123      40.53      -90.21         42.45
123      40.56      -90.45         42.45
123      40.63      -91.34         42.45
Run Code Online (Sandbox Code Playgroud)

最终代码

for row in df.itertuples():
    def min_distance(row):
        here = (row.Latitude, row.Longitude)
        return min(haversine(here, coord) for coord in coords)
    df['Nearest_Distance'] = df.apply(min_distance, axis=1)
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 3

您正在寻找pandas.DataFrame.apply(). 就像是:

代码:

df['output'] = df.apply(min_distance, axis=1)
Run Code Online (Sandbox Code Playgroud)

测试代码:

df = pd.read_fwf(StringIO(u'''
        AcctId   Latitude   Longitude
        123      40.50      -90.13
        123      40.53      -90.21
        123      40.56      -90.45
        123      40.63      -91.34'''), header=1)

coords = [
    (41.45, -95.13),
    (39.53, -100.42),
    (45.53, -95.32)
]

from haversine import haversine

def min_distance(row):
    here = (row.Latitude, row.Longitude)
    return min(haversine(here, coord) for coord in coords)

df['output'] = df.apply(min_distance, axis=1)

print(df)
Run Code Online (Sandbox Code Playgroud)

结果:

   AcctId  Latitude  Longitude      output
0     123     40.50     -90.13  432.775598
1     123     40.53     -90.21  425.363959
2     123     40.56     -90.45  404.934516
3     123     40.63     -91.34  330.649766
Run Code Online (Sandbox Code Playgroud)