Skip to main content
 首页 » 编程设计

python之使用 dataframe.loc 将信息从一个数据帧调用到另一个数据帧的更有效方法

2024年11月24日9Terrylee

我想知道您是否可以提出一种更有效的方法?

我有两个数据框如下: 1) 一个包含各种“站”位置的数据框:

   StationNames   Lat          Long 
0   St1         1.30405        103.77350 
1   H2          1.30414        103.77355 
2   H11         1.30446        103.77375 

2) 带有我在不同站点时的时间戳的数据框:

               Description        Session       Survey 
Local            
2018-10-06 09:48:30   St1       Oct06_Morning   Survey 
2018-10-06 09:56:30   St1       Oct06_Morning   Survey 
2018-10-06 09:58:30   H2        Oct06_Morning   NoSurvey 
 

现在我想在第二个中添加一列,它根据站名(描述)获取地址(纬度、经度)。 我做了一个循环,但听起来效率很低。有什么建议么? 谢谢, 尼金

TimeStamps['Lat']=0.00 
TimeStamps['Lng']=0.00 
for i in range(TimeStamps.shape[0]): 
    ALong=StationAddress.loc[StationAddress.StationNames==TimeStamps.Description[i],'Long'] 
    Blat=StationAddress.loc[StationAddress.StationNames==TimeStamps.Description[i],'Lat'] 
    #print i, ALong, Blat 
    TimeStamps['Lng'][i]=ALong 
    TimeStamps['Lat'][i]=Blat 

请您参考如下方法:

您可以使用 merge()功能。

所以如果你的框架是:

StationAddress = pd.DataFrame(data=[['St1',1.30405, 103.77350], ['H2',1.30414, 103.77355],['H11',1.30446, 103.77355]],  
               columns=['StationNames', 'Lat','Long']) 
 
TimeStamps = pd.DataFrame(data=[['2018-10-0609:48:30','St1','Oct06_Morning', 'Survey'], ['2018-10-06 09:56:30','St1','Oct06_Morning', 'Survey'],['2018-10-06 09:58:30','H2','Oct06_Morning', 'NoSurvey']],  
               columns=['local','Description', 'Session','Survey']) 

试试这个:

TimeStamps.merge(StationAddress,  
                               left_on='Description', right_on='StationNames',   
                                how='left', left_index=True).set_index('local')