【问题标题】:For loop error, SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame对于循环错误,SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
【发布时间】:2018-10-25 09:47:10
【问题描述】:

我试图用 GPS 坐标计算半径 100 米内的地点。我的数据有 4 列,如下所示;

Index     Longitude    Latitude      Count
1         35.897654    26.568987       0
2         32.98717     23.897740       0
3         36.23245     34.243246       0
.          ....         ....          ....
.          ....         ....          ....

我用 Haversine 方法计算了与坐标的距离。我把它描述为一个函数。

haversine([x1,y1],[x2,y2]) 给出 GPS 坐标之间的米。

我的问题出现在下面的代码中;

for x in range(0,25486):
    for y in range(1,25486):
        a = haversine([cr.iloc[x][0],cr.iloc[x][1]],[cr.iloc[y][0],cr.iloc[y][1]])
        if a <= 100 and a > 0:
            cr.iloc[x][2]=cr.iloc[x][2]+1

它会引发此错误;

ma​​in:5: SettingWithCopyWarning: 试图在 DataFrame 中的切片副本上设置值

请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

我检查了文档,但找不到有用的东西或者我不明白。

我做错了什么? 执行此嵌套循环操作的正确方法是什么?

提前致谢。

【问题讨论】:

    标签: python for-loop nested-loops


    【解决方案1】:
    cr.iloc[x][2]=cr.iloc[x][2]+1
    

    此代码未在数据框中设置值

    我已经改成;

    for x in range(0,25486):
        t=0
        for y in range(0,25486):
            a = haversine([cr.iloc[x][1],cr.iloc[x][2]],[cr.iloc[y][1],cr.iloc[y][2]])
            if a <= 400 and a > 0:
                t = t+1   
        cr.set_value(x,'Adet',t)
    

    【讨论】:

      【解决方案2】:

      通过查看您的问题,我没有得到答案,但我对使用 .set_value 的研究使我得到了非常相似的东西。

      我正在使用.at[index, 'column'] = value

      我的代码:

      for index, row in customersOnMap.iterrows():
      x = row.loc['customer_zip_code_prefix']
      if x in list_zip_code.geolocation_zip_code_prefix.values:
          lat = list_zip_code[list_zip_code.geolocation_zip_code_prefix == x].geolocation_lat.values[0]
          long = list_zip_code[list_zip_code.geolocation_zip_code_prefix == x].geolocation_lng.values[0]
          customersOnMap.at[index, 'geolocation_lat'] = lat
          customersOnMap.at[index, 'geolocation_lng'] = long
      else:
          print('Couldn t find the zip code', x, 'in the list.')
      

      更多信息的链接:

      https://www.dataindependent.com/pandas/pandas-set-values/

      【讨论】:

        猜你喜欢
        • 2022-12-02
        • 2022-12-02
        • 2022-12-02
        • 1970-01-01
        • 2014-02-13
        • 2022-12-02
        • 2022-12-01
        • 2022-12-27
        • 2016-02-01
        相关资源
        最近更新 更多