【行政区编码对应表及生态等级数据的制作】-python
行政区编码对应表及生态等级数据的制作
- 获取高德的行政区数据-district_data.json
- 得到高德的api_key
- 使用request发送带参的get请求
- 完整代码:请求中国的整体数据,保存成json文件
- 制作行政区名信息表-district_data.xlsx
- 完整代码
- 制作行政区生态等级数据-districtLevels.json
- districtLevels.json的格式
- 生态等级分级
- 完整代码
使用python借助高德的api接口实现
获取高德的行政区数据-district_data.json
得到高德的api_key
(服务平台得是web服务)
使用request发送带参的get请求
# 定义高德地图行政区查询接口URL
url = "https://restapi.amap.com/v3/config/district"
# 请求参数
params = {
'key': api_key,
'keywords': '中国',
'subdistrict': 3, # 获取到区县级别
'extensions': 'all' # 获取详细信息
}
# 发送请求
response = requests.get(url, params=params)
完整代码:请求中国的整体数据,保存成json文件
# -*- coding: utf-8 -*-
# @Author : longbhu
# @Time : 2024/12/11 16:40
# @Function:
import requests
import json
# 高德地图API密钥
api_key = 'ac2c3314c22api_key082a9903' # 替换为你的高德地图API密钥
# 定义高德地图行政区查询接口URL
url = "https://restapi.amap.com/v3/config/district"
# 请求参数
params = {
'key': api_key,
'keywords': '中国',
'subdistrict': 3, # 获取到区县级别
'extensions': 'all' # 获取详细信息
}
# 发送请求
response = requests.get(url, params=params)
# 检查响应状态码
if response.status_code == 200:
data = response.json()
if data['status'] == '1':
# 获取行政区数据
district_data = data['districts']
# 保存到JSON文件
output_file_path = 'district_data.json'
with open(output_file_path, 'w', encoding='utf-8') as f:
json.dump(district_data, f, ensure_ascii=False, indent=4)
print(f"行政区数据已保存到 {output_file_path}")
else:
print(f"请求失败: {data['info']}")
else:
print(f"请求失败: {response.status_code}")
输出为output_file_path = ‘district_data.json’
制作行政区名信息表-district_data.xlsx
根据上面的district_data.json得到district_data.xlsx(行政区名信息表)
包含如下字段adcode,province_name,city_name,district_name,full_name
完整代码
# -*- coding: utf-8 -*-
# @Author : longbhu
# @Time : 2024/12/11 17:12
# @Function: 输出district_data.xlsx 行政区名信息表 包含如下字段adcode,province_name,city_name,district_name,full_name
import json
import pandas as pd
def extract_district_info(data):
extracted_data = []
def recursive_extract(items, province_name=None, city_name=None, district_name=None):
for item in items:
adcode = item.get('adcode')
name = item.get('name')
level = item.get('level')
if level == 'province':
province_name = name
city_name = None # Reset city_name when entering a new province
district_name = None # Reset district_name when entering a new province
elif level == 'city':
city_name = name
district_name = None # Reset district_name when entering a new city
elif level == 'district':
district_name = name
# 拼接省市县名称
full_name = f"{province_name}{' ' + city_name if city_name else ''}{' ' + district_name if district_name else ''}"
extracted_data.append({
'adcode': adcode,
'province_name': province_name,
'city_name': city_name,
'district_name': district_name if level == 'district' else None,
'full_name': full_name # 新增的 full_name 列
})
if 'districts' in item and isinstance(item['districts'], list):
recursive_extract(item['districts'], province_name, city_name, district_name)
recursive_extract(data)
return extracted_data
# 读取 JSON 文件
with open('F:\\code\\test\\Gui\\calculator\\dat_to_excel\\calc_percent_excel\\行政区代码对应表\\district_data.json',
'r', encoding='utf-8') as file:
data = json.load(file)
# 提取 adcode 和 name 信息
extracted_data = extract_district_info(data)
# 创建 DataFrame
df = pd.DataFrame(extracted_data)
# 保存到 Excel 文件
output_file = 'F:\\code\\test\\Gui\\calculator\\dat_to_excel\\calc_percent_excel\\行政区代码对应表\\district_data.xlsx'
df.to_excel(output_file, index=False)
print(f"数据已成功保存到 {output_file}")
制作行政区生态等级数据-districtLevels.json
根据district_data.xlsx(行政区名信息表)和行政区生态区等级排名的excel文件(包含 code2014 和 rank 列的 Excel 文件)生成一个json文件(districtLevels.json)
districtLevels.json的格式
{
"provinces": [],
"cities": [],
"districts": [
{
"adcode": 410323,
"name": "新安县",
"value": 3,
"eco_level": 3
},
]
}
生态等级分级
按照0-100、101-500、501-1500及1500以下分为四个等级
eco_level_dict = {}
for index, row in eco_excel_data.iterrows():
code2014 = number(row['CODE2014'])
rank = row['Rank']
if rank < 100:
eco_level = 1
elif 101 <= rank <= 500:
eco_level = 2
elif 501 <= rank <= 1500:
eco_level = 3
else:
eco_level = 4
eco_level_dict[code2014] = eco_level
(其他分级方法待开发···)
完整代码
县级_code_sort_3.xlsx
# -*- coding: utf-8 -*-
# @Author : longbhu
# @Time : 2024/12/12 11:47
# @Function: 根据district_data.xlsx(行政区名信息表)生成一个json文件, 形式如下:
#
# "districts": [
# {
# "adcode": 410323,
# "name": "新安县",
# "value": 3,
# "eco_level": 3
# },
import pandas as pd
import json # 导入 json 模块
from PIL.ImImagePlugin import number
# 读取 Excel 文件
excel_path = 'F:\\code\\test\\Gui\\calculator\\dat_to_excel\\calc_percent_excel\\行政区代码对应表\\district_data.xlsx'
excel_data = pd.read_excel(excel_path)
# 读取包含 code2014 和 rank 列的 Excel 文件
eco_excel_path = './县级_code_sort_3.xlsx'
eco_excel_data = pd.read_excel(eco_excel_path)
# 将 code2014 和 rank 列的数据映射到一个字典中
eco_level_dict = {}
for index, row in eco_excel_data.iterrows():
code2014 = number(row['CODE2014'])
rank = row['Rank']
if rank < 100:
eco_level = 1
elif 101 <= rank <= 500:
eco_level = 2
elif 501 <= rank <= 1500:
eco_level = 3
else:
eco_level = 4
eco_level_dict[code2014] = eco_level
# 初始化三个空列表来存储不同级别的 JSON 数据
provinces = []
cities = []
districts = []
# 遍历每一行数据
for index, row in excel_data.iterrows():
adcode = number(row['adcode'])
province_name = row['province_name']
city_name = row['city_name']
district_name = row['district_name']
# 获取 eco_level,默认为 None
# print(eco_level_dict[adcode])
eco_level = eco_level_dict.get(adcode, 4)
# 根据不同的级别设置 name 和 value
if pd.notna(district_name) and district_name != "":
districts.append({
"adcode": adcode,
"name": district_name,
"value": 3 , # 区级行政区对应的 value 为 3
"eco_level": eco_level
})
elif pd.notna(city_name) and city_name != "":
cities.append({
"adcode": adcode,
"name": city_name,
"value": 2 # 市级行政区对应的 value 为 2
})
elif pd.notna(province_name) and province_name != "":
provinces.append({
"adcode": adcode,
"name": province_name,
"value": 1 # 省级行政区对应的 value 为 1
})
# 创建最终的 JSON 数据结构
json_data = {
"provinces": provinces,
"cities": cities,
"districts": districts
}
# 保存 JSON 数据到文件
json_output_path = 'districtLevels.json'
with open(json_output_path, 'w', encoding='utf-8') as json_file:
json.dump(json_data, json_file, ensure_ascii=False, indent=4)
print(f"JSON 数据已成功保存到 {json_output_path}")