Skip to main content
 首页 » 编程设计

python之Pandas之使用 itertuples 创建列

2025年02月15日9jackei

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

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

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 

期望的输出:

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 

实际输出:

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 

最终代码

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) 

请您参考如下方法:

您正在寻找pandas.DataFrame.apply() .像这样的东西:

代码:

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

测试代码:

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) 

结果:

   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