python - 这个熊猫阅读excel问题有什么问题?
问题描述
我想从一个excel文件中读取大量坐标(大约14000+),并通过百度地图的API将它们转换为特定的地址。但是程序只能读取最后一个坐标。我的代码有问题吗?这是我的代码:
import requests
import pandas as pd
import json
df = pd.read_excel(r'C:\Users\YDC\Desktop\JW.xlsx')
fw = open(r'C:\Users\YDC\Desktop\result.txt', "w", encoding="utf-8")
for i in range(0,len(df)):
t1=df.iloc[i]['lat']
t2=df.iloc[i]['lng']
baiduUrl = "http://api.map.baidu.com/geocoder/v2/?ak=21q0bMSgjdDVe0gLmjClrsuyUA1mvsRx&callback=renderReverse&location=%s,%s&output=json&pois=0" % (t1, t2)
req = requests.get(baiduUrl)
content = req.text
content = content.replace("renderReverse&&renderReverse(", "")
content = content[:-1]
baiduAddr = json.loads(content)
country = baiduAddr["result"]["addressComponent"]["country"]
city = baiduAddr["result"]["addressComponent"]["city"]
province = baiduAddr["result"]["addressComponent"]["province"]
new_line = country + "|" + city + "|" + province
fw.write(new_line)
fw.write("\n")
print(new_line)
只能打印最后一个坐标的地址:捷克|Olomouc|Olomouc
如何获得这些坐标的其余部分? 这是excel文件中的数据
解决方案
这看起来像一个经典的 python 循环陷阱。
考虑一下:
for i in range(0, 10):
foo = i
print (foo) # notice the indentation
输出
9
这是因为在 python 中,变量范围是这样的,您仍然可以从循环外部引用在循环内部定义的变量。
一个非常简单的修复,如下所示:
for i in range(0, 10):
foo = i
print (foo)
给出预期的结果
0
1
2
3
4
5
6
7
8
9
在您的情况下,只需确保第 12 行以后的行向右缩进一级。
推荐阅读
- c++ - 如何配置 CMake 以特定顺序构建多个项目?
- python - OSError:[Errno 24] 使用 pytorch 数据加载器时 Windows 10 中打开的文件过多
- html - 删除社交菜单页脚
- javascript - n 的值如何在递归中减小
- javascript - 您可以一次要求所有节点模块吗
- google-apps-script - 使用 onEdit 触发器将 Google 日历事件自动刷新到 Google Sheers
- java - 如何将通知从 Web 应用程序发送到特定用户到移动应用程序
- unicode - 为什么 Unicode 有 2 个空格?有什么不同?
- javascript - 使用 Cookie 记录脚本单击 3 次后替换元素 [帮助]
- python-3.x - 关于loopinbg的问题 - 试图从列表中找到一个素数