尝试填充纬度/经度列时的所有NaN值

问题描述

我正在尝试从一个DataFrame解释纬度/经度,然后将其放入另一个。但是,当我尝试这样做时,最终我的列中得到了所有NaN值。

我认为显示我的问题的最好方法显示一些代码

首先,这是我的第一个DataFrame,称为happiness_data 以下代码提供以下输出

happiness_data.head()

enter image description here

接下来,我有一个名为country_coord_data的信息。该帧的.head()给出以下输出

enter image description here

最后,这是我尝试更改幸福DF的纬度和经度列的代码

country_names = happiness_data["Country or region"]
country_coord_data.loc[country_coord_data["name"] == "Finland"]["latitude"]

for country in country_names:
    for country2 in country_coord_data["name"]:
        if country==country2:
            happiness_data.loc[happiness_data["Country or region"] == country,"Latitude"] = country_coord_data.loc[country_coord_data["name"] == country,"latitude"]
            happiness_data.loc[happiness_data["Country or region"] == country,"Longitude"] = country_coord_data.loc[country_coord_data["name"] == country,"longitude"]
happiness.head()

最后,这是结果输出

enter image description here

我认为它有两个主要问题:

  1. 代码未返回正确的纬度/经度。
  2. 这效率极低,但是我想不出更好的方法解决这个问题。

任何帮助将不胜感激!

解决方法

正如您所说,我只会使用https://www.supremenewyork.com/shop/tops-sweaters/deshwjqp5/i640qb2pu 进行左联接,除非出于特殊原因,不建议在数据帧中使用for循环。我将使用的代码如下:

merge

您需要进行一些df操作才能删除旧列,但这足够了。