使用pd.merge映射一个数据框中来自另一个数据框的多个列的值

时间:2020-01-07 07:51:23

标签: python pandas

我有一个数据框( df3

df3 = pd.DataFrame({
    'Origin':['DEL','BOM','AMD'],
    'Destination':['BOM','AMD','DEL']})

包含旅行数据,其中包含出发地/目的地,并且我正尝试使用3个字母的城市代码( df_s3 )来映射始发地和目的地机场的纬度和经度。

df_s3 = pd.DataFrame({
    'iata_code':['AMD','BOM','DEL'],
    'Lat':['72.6346969603999','72.8678970337','77.103104'],
    'Lon':['23.0771999359','19.0886993408','28.5665']})

我尝试一次将它们映射一个,即

df4=pd.merge(left=df3,right=df_s3,how='left',left_on=['Origin'],right_on=['iata_code'],suffixes=['_origin','_origin'])
df5=pd.merge(left=df4,right=df_s3,how='left',left_on=['Destination'],right_on=['iata_code'],suffixes=['_destination','_destination'])

这将更新数据框中的值,但与原始纬度/经度相对应的列具有“ _destination”作为后缀

通过结合两者,我什至获得了理想的远景

df4=pd.merge(left=df3,right=df_s3,how='left',left_on=['Origin','Destination'],right_on=['iata_code','iata_code'],suffixes=['_origin','_destination'])

这两个似乎都不起作用。关于如何使其在较大的数据集中工作,同时保持较低的处理时间的任何建议。

2 个答案:

答案 0 :(得分:1)

您的解决方案几乎是正确的。但是您需要在第二次合并中指定原点后缀:

f = lambda x: x.split('.')[-1]
df = json_normalize(j).rename(columns=f)
print (df)
       timestamp tenant tstable    user     ID type     ID2      a      b
0  1500079519064    dxy    data  writer  99909  fff  565789  0.003  0.011

在第一次合并中,由于没有重叠,因此不需要指定任何后缀。在第二个合并中,您需要为右侧和左侧指定后缀。右侧是从原点开始的经度和纬度,左侧是从目的地开始的经度和纬度。

答案 1 :(得分:0)

您可以尝试将类似以下的功能应用于每一列:

def from_place_to_coord(place: str):
    if place in df_s3['iata_code'].to_list():
        Lat = df_s3[df_s3['iata_code'] == place]['Lat'].values[0]
        Lon = df_s3[df_s3['iata_code'] == place]['Lon'].values[0]
        return Lat, Lon
    else:
        print('Not found')

然后:

df3['origin_loc'] = df3['Origin'].apply(from_place_to_coord)
df3['destination_loc'] = df3['Destination'].apply(from_place_to_coord)

根据位置,它还会再返回2列带有纬度,经度的元组