如何合并两个本质上加载到形状文件(geojson)中的json文件

问题描述 投票:0回答:1

我有两个 json 文件,一个用于英格兰,另一个用于苏格兰。我尝试将两者结合起来并将它们加载为形状文件,但是 geopandas 只能识别其中之一。有没有办法组合两个 json 文件的多边形?

解决方案如下:

import pandas as pd 
import geopandas as gpd

file_list = ['topo_eer England.json','topo_eer Scotland.json']
dfs = [] # an empty list to store the data frames
for file in file_list:
 data = pd.read_json(file, lines=True) # read data frame from json file
 dfs.append(data) # append the data frame to the list

temp = pd.concat(dfs, ignore_index=True) # concatenate all the data frames in the list.
temp.to_json('temp.json', orient='records', lines=True)
df = gpd.read_file("temp.json")
df.plot()

输出(仅返回英格兰..):

python geopandas
1个回答
0
投票

假设您确实需要将两个文件合并为一个(并且能够绘制从该文件构建的数据框),您可以将两个 JSON 文件读取为地理数据框,然后将它们与 pandas.concat 连接起来,保存将连接的数据框连接到新的 JSON 文件,将其读取到特殊的地理数据框,最后绘制该特殊的地理数据框:

import pandas as pd 
import geopandas as gpd
import matplotlib.pyplot as plt

# read json files to geo data frames
sc_df = gpd.read_file("topo_eer_Scotland.json")
en_df = gpd.read_file("topo_eer_England.json")

# concatenate them using pandas
df = pd.concat([en_df, sc_df])
# save the concatenated data frame as a json file, if required
df.to_file("topo_eer_Scotland_and_England.json")
# read the resulting json file to a test geo data frame
test_df = gpd.read_file("topo_eer_Scotland_and_England.json")
# plot the test geo data frame to see how it works
test_df.plot()

plt.show()

结果:

但是,如果您不关心组合的 JSON 文件,您可以简单地在相同的 matplotlib 轴上一一绘制相应的地理数据框:

import pandas as pd 
import geopandas as gpd
import matplotlib.pyplot as plt

gdf = gpd.read_file("topo_eer_England.json")
df = gpd.read_file("topo_eer_Scotland.json")
fig, ax = plt.subplots()
gdf.plot(ax=ax, color='red')
df.plot(ax=ax, color='blue')

plt.show()

这样,就可以很容易地使用一些漂亮的颜色来区分这两个国家:

© www.soinside.com 2019 - 2024. All rights reserved.