首页 > 解决方案 > SettingWithCopyWarning 问题 - 如何在 for 循环中创建我的 df 副本?

问题描述

我正在尝试运行此代码:

for x in range(len(df10)):
    try:
        time.sleep(1) #to add delay in case of large DFs
        geocode_result = gmaps.geocode(df10['Address'][x])
        df10['lat'][x] = geocode_result[0]['geometry']['location'] ['lat']
        df10['long'][x] = geocode_result[0]['geometry']['location']['lng']
    except IndexError:
        print("Address was wrong...")
    except Exception as e:
        print("Unexpected error occurred.", e )

我希望 for 循环遍历地址列表,该列表现在存储在名为 的 pandas 数据框的列中df10['Address'],然后应用 Google 地理编码服务来提取每行的经度和纬度并将它们保存为原始数据框的列.

当我尝试这样做时,我收到以下错误:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

我知道这是因为我试图覆盖原始数据帧,但我真的很难找到可行的替代代码。

希望有人可以提供帮助!

标签: pythonpandasloopsgeocoding

解决方案


假设df10它本身不是另一个 DataFrame 的一部分:

df10.loc[df10.index[x], 'lat'] = geocode_result[0]['geometry']['location'] ['lat']

推荐阅读