如何用python根据excel中地址批量查找高德坐标系的经纬度
时间: 2023-06-02 16:02:37 浏览: 82
要用Python根据Excel中地址批量查找高德坐标系的经纬度,可以使用高德地图API。以下是具体步骤:
1. 首先,需要导入以下库:
```python
import pandas as pd
import requests
import json
```
2. 读取Excel文件,并提取地址信息:
```python
df = pd.read_excel('file.xlsx')
addresses = df['Address'].tolist()
```
其中,'Address'是Excel中存储地址的列名。
3. 构造请求URL,并发送请求获取经纬度信息:
```python
key = 'your_amap_api_key'
url = 'https://restapi.amap.com/v3/geocode/geo?key={}&address={}'.format(key,address)
response = requests.get(url)
```
需要将'your_amap_api_key'替换成自己的高德地图开发者Key,address则是当前循环到的地址信息。
4. 解析返回的JSON数据,并提取经纬度信息:
```python
if response.status_code == 200:
response_json = json.loads(response.text)
if response_json.get('count') == '1':
location = response_json['geocodes'][0]['location']
longitude, latitude = location.split(',')
else:
longitude, latitude = None, None
else:
longitude, latitude = None, None
```
如果请求成功,会返回一个JSON数据,其中包含了经纬度信息。首先需要判断返回结果是否成功,如果成功则解析JSON数据并提取经纬度信息,如果不成功则将经纬度信息设为None。
5. 将经纬度信息保存到DataFrame中:
```python
df['longitude'] = longitude
df['latitude'] = latitude
```
其中,'longitude'和'latitude'分别是存储经度和纬度的列名。
6. 将结果保存到Excel文件中:
```python
df.to_excel('result.xlsx', index=False)
```
完整代码如下:
```python
import pandas as pd
import requests
import json
df = pd.read_excel('file.xlsx')
addresses = df['Address'].tolist()
key = 'your_amap_api_key'
for address in addresses:
url = 'https://restapi.amap.com/v3/geocode/geo?key={}&address={}'.format(key,address)
response = requests.get(url)
if response.status_code == 200:
response_json = json.loads(response.text)
if response_json.get('count') == '1':
location = response_json['geocodes'][0]['location']
longitude, latitude = location.split(',')
else:
longitude, latitude = None, None
else:
longitude, latitude = None, None
df.loc[df['Address'] == address, 'longitude'] = longitude
df.loc[df['Address'] == address, 'latitude'] = latitude
df.to_excel('result.xlsx', index=False)
```