python - 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)
。我尝试更改它们并重新运行循环,但它是相同的。这也是一个耗时的过程,因为有数千个位置。
解决方案
没有看到数据就很难提供帮助,但这可能会对您有所帮助。
- 将来,请提供您的数据的最小示例,以便我们可以使用它并更好地帮助您。
- 此外,你不应该在没有提供确切错误的情况下使用'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())
推荐阅读
- python - 删除行 < x 以在 Pandas 中创建绘图
- android - RecyclerView 不会将从 Firestore 检索到的数据加载到 ItemView
- javascript - 使用 Django Models 通过 jQuery 分配 HTML div
- java - Java多维映射值?
- php - 如何在 Laravel 中查看服务器日志?
- javascript - 如何使用 javascrip 调整浏览器?
- arrays - 将一个对象从一个数组推送到另一个数组javascript
- html - 根据其他div的高度移动div
- r - R Shiny ggplot 颜色美学对输入有反应
- perl - 使用 substr 在字符串前面添加更快吗?