SettingWithCopyWarning 问题 - 如何在 for 循环中创建 df 的副本?

时间:2021-05-21 12:47:59

标签: python pandas loops geocoding

我正在尝试运行此代码:

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 循环遍历地址列表,该列表现在存储在名为 df10['Address'] 的 Pandas 数据框的列中,然后应用 Google 地理编码服务提取每行的经度和纬度,然后将这些保存为原始数据框的列。

当我尝试这样做时,出现以下错误:

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

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

希望有人能帮忙!

2 个答案:

答案 0 :(得分:0)

假设 df10 本身不是另一个 DataFrame 的切片:

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

答案 1 :(得分:0)

通过应用返回多个值的函数来创建新列。

虚假数据:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4,5,6],'b':list('abcdef')})

>>> df
   a  b
0  1  a
1  2  b
2  3  c
3  4  d
4  5  e
5  6  f

构造一个函数,其参数为一行并对其中一列进行运算。

def f(row):
    lat = row['a'] * 2
    lon = row['a'] % 2
    return lat,lon

将该函数应用于 DataFrame 并将结果分配给新列。

>>> df[['lat','lon']] = df.apply(f,axis=1,result_type='expand')
>>> df
   a  b  lat  lon
0  1  a    2    1
1  2  b    4    0
2  3  c    6    1
3  4  d    8    0
4  5  e   10    1
5  6  f   12    0
>>>

expand 参数将函数的类似列表的结果转换为列。

您没有提供任何示例数据,我也没有安装 gmap,但我想您的代码应该如下所示:

def g(row):
    g_result = gmaps.geocode(row['Address'])
    lat = g_result[0]['geometry']['location'] ['lat']
    lon = g_result[0]['geometry']['location']['lng']
    return lat,lon

并像这样使用:

df[['lat','lon']] = df.apply(g,axis=1,result_type='expand')