首页 > 解决方案 > Pandas Python 3中列的For循环逻辑错误

问题描述

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

我有的

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

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

标签: pythonpandasfor-looplogic

解决方案


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

  • 将来,请提供您的数据的最小示例,以便我们可以使用它并更好地帮助您。
  • 此外,你不应该在没有提供确切错误的情况下使用'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())

推荐阅读