【问题标题】:All NaN values when trying to fill latitude/longitude columns尝试填充纬度/经度列时的所有 NaN 值
【发布时间】:2021-02-19 15:11:25
【问题描述】:

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

我认为显示我的问题的最佳方式是显示一些代码!

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

happiness_data.head()

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

最后,这是我尝试更改幸福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()

最后,这是结果输出:

在我看来,主要有两个问题:

  1. 代码未返回正确的纬度/经度。
  2. 这非常低效,但我想不出更好的方法来做到这一点。

任何帮助将不胜感激!

【问题讨论】:

  • 为什么不合并?

标签: pandas geo


【解决方案1】:

我会简单地使用merge 执行左连接,正如您所说,除非出于非常特定的原因,不鼓励使用带有数据帧的 for 循环。我将使用的代码如下:

happiness_data = happiness_data.merge(country_cord_data,how='left',left_on='Country or region',right_on='name')

您需要一些 df 操作来删除旧列,但这应该足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    相关资源
    最近更新 更多