【问题标题】:Error in For Loop Logic for a Column in Pandas Python 3Pandas Python 3中列的For循环逻辑错误
【发布时间】:2020-01-08 11:03:40
【问题描述】:

我有一个位置列表。对于位置列中的每个位置,都有一个函数可以找到它的坐标,如果它们还没有的话。对所有人执行此操作。循环复制所有行中的最后一个纬度和经度值,这是不应该做的。我在哪里做错了?

我有什么

location           gpslat gpslong
Brandenburger Tor  na     na
India Gate         na     na
Gateway of India   na     na

我想要什么

location           gpslat gpslong
Brandenburger Tor  52.16  13.37
India Gate         28.61  77.22
Gateway of India   18.92  72.81

我得到了什么

location           gpslat gpslong
Brandenburger Tor  18.92  72.81
India Gate         18.92  72.81
Gateway of India   18.92  72.81

我的代码

i = 0
for location in df.location_clean:
    try:
        if np.isnan(float(df.gpslat.iloc[i])) == True:
                df.gpslat.iloc[i], df.gpslong.iloc[i] = find_coordinates(location)
                print(i, "Coordinates Found for --->", df.location_clean.iloc[i])
        else:
            print(i,'Coordinates Already Present')
    except:
        print('Spelling Mistake Encountered at', df.location_clean.iloc[i], 'Moving to NEXT row')
        continue
    i = i + 1

我想,我在索引 i 或语句 df.gpslat.iloc[i], df.gpslong.iloc[i] = find_coordinates(location) 上犯了一个逻辑错误。我尝试更改它们并重新运行循环,但它是相同的。这也是一个耗时的过程,因为有数千个地点。

【问题讨论】:

  • 请将您的df 粘贴到您的问题中
  • 根据您提供的示例,我建议您查看您的 find_coordinates() 函数返回的内容 - 它实际上返回不同的值吗?
  • 是的,它确实返回了不同的值,因为我先检查了它,然后我将它应用到了那里。
  • 它正在工作。在任何处理开始之前,我增加了浏览器窗口的等待时间。谢谢Cribber

标签: python pandas for-loop logic


【解决方案1】:

没有看到数据就很难提供帮助,但这可能会对您有所帮助。

  • 以后,请提供您的数据的最小示例,以便我们可以使用它并更好地帮助您。
  • 此外,您不应在未提供确切错误的情况下使用 'except' - 在这种情况下,您的 except 会捕获所有错误,即使除了您的“拼写错误”之外还有其他错误 - 在您没有注意到的情况下!
  • 在对数据帧进行迭代时,使用 iterrows() - 它使其更具可读性,并且您不必使用额外的变量
  • 使用 iloc 会打开 pandas 的 SettingWithCopyWarning(参见此处:https://www.dataquest.io/blog/settingwithcopywarning/),尽量避免。

代码如下:

# ____ Preparation ____ 
import pandas as pd
import numpy as np

lst = [['name1', 1, 3]
      ,['name2',1, 3]
      ,['name3',None, None]
      ,['name4',1, 3]
       ]
df = pd.DataFrame(lst,    columns =['location', 'gpslat', 'gpslong',])
print(df.head())

# ____ YOUR CODE ____ 
for index, row in df.iterrows():
       try:
              if np.isnan(float(row['gpslat'])) == True:
                     lat, long = find_coordinates(row['location'])
                     print(lat,long)
                     df.at[index, 'gpslat'] = lat
                     df.at[index, 'gpslong'] = long

       except TypeError:  # exchange this with the exact error which you want to  catch
              print('Spelling Mistake Encountered at', row['location'], ' in row ', index, 'Moving to NEXT row')
              continue
print(df.head())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多