首页 > 解决方案 > 这个熊猫阅读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

解决方案


这看起来像一个经典的 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 行以后的行向右缩进一级。

相关:Python 'for' 循环中的作用域


推荐阅读