繁体   English   中英

尝试将一个数据帧中的值与另一个数据帧中的值匹配(python)

[英]Trying to match values in one data frame to values in another data frame (python)

我目前有一个 dataframe A 由一列 (code1) 国家代码组成,例如 CA、RU、US 等。我还有另一个 dataframe B 有 3 列,其中第一列包含所有可能的国家代码,第二列有经度值第三个有纬度值。 我试图遍历 A,在第一列中获取第一个国家代码,将其与 B 第一列中的国家代码匹配,然后获取该国家的相关经度和纬度,依此类推。 我计划创建一个新的 dataframe 包含来自 A(第一列)的代码和新提取的经度和纬度值。

到目前为止,我的 function 看起来如下

def get_coords():
    for i in range(len(A["code1"])):
        for j in range(len(B["code"])):
            if A["code1"[i] = B["code"[j]: #if the country codes match
                latitude = B["lat"][j] #gets the latitude of the matched country code
                longitude = B["long"][j] #gets the longitude

但是,这似乎效率低下,我不确定它是否正确匹配数据帧中的代码。 有没有更好的方法来实现我想要实现的目标?

供参考len(A["code1"]) = 581len(B["code"] = 5142

这是数据的示例输入:

A = pd.DataFrame({'code1': ['US', 
                   'RU', 'AO', 'ZW']})

B = pd.DataFrame({'code': ['US', 'ZW', 'RU', 'YE', 'AO'], 
                   'long': [65.216000, 65.216000,18.500000,-63.032000,19.952000], 'lat': [12.500000, 33.677000,-12.500000,18.237000,60.198000]})

我试图让 output 看起来像

A = pd.DataFrame({'code1': ['US', 'RU', 'AO', 'ZW'], 'longitude':[65.216000,18.500000, 19.952000, 65.216000], 'latitude': [12.500000, -12.500000, 60.198000, 33.677000]})

使用pd.merge并指定要合并的left_on列以及right_on列,因为要合并的两列具有不同的列名。 然后, .drop的多余列。

A = pd.merge(A,B,how='left',left_on='code1',right_on='code').drop(['code'], axis=1)

output:

    code1   long        lat
0   US      65.216      12.500
1   RU      18.500      -12.500
2   AO      19.952      60.198
3   ZW      65.216      33.677
n [108]: A = pd.DataFrame({'code1': ['US',
     ...:                    'RU', 'AO', 'ZW']})

In [109]: B = pd.DataFrame({'code': ['US', 'ZW', 'RU', 'YE', 'AO'],
     ...:                    'long': [65.216000, 65.216000,18.500000,-63.032000,19.952000], 'lat': [12.500000, 33.67700
     ...: 0,-12.500000,18.237000,60.198000]})

In [110]: A.rename({"code1":"code"},axis=1,inplace=True)

In [111]: A = pd.merge(A,B, on="code").rename({"code":"code1"},axis=1)

In [112]: A
Out[112]:
  code1    long     lat
0    US  65.216  12.500
1    RU  18.500 -12.500
2    AO  19.952  60.198
3    ZW  65.216  33.677

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM