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

2024-09-29 23:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道你能不能提出一个更有效的方法

我有两个数据帧,如下所示: 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

现在我想在第二列中添加一个列,它根据站点名称(Description)获取地址(Lat,Long)。 我做了一个循环,但听起来效率很低。有什么建议吗? 谢谢, 尼金

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

Tags: 数据站点h2descriptionsurveylonglatmorning
1条回答
网友
1楼 · 发布于 2024-09-29 23:20:23

您可以使用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')

相关问题 更多 >

    热门问题