使用geopandas裁剪行政区域地图

2024-06-20 18:09:31 浏览数 (4)

前言:这个小技巧前面白化的推文也使用过,专门拿出来写一篇

版本 python 3.9

代码语言:javascript复制
代码语言:javascript复制
import numpy as np
import geopandas as gpd
import matplotlib.pyplot as plt



# 读取全国地图数据
china_map = gpd.read_file('/home/mw/input/china1656/china_map/china_map/China_Province_2022.shp')
代码语言:javascript复制
china_map

省级码

省类型

ENG_NAME

VAR_NAME

FIRST_GID

FIRST_TYPE

year

geometry

0

北京市

110000

直辖市

Beijing

Běi Jīng

110000

Municipality

2022

POLYGON ((117.38335 40.22647, 117.38557 40.224...

1

天津市

120000

直辖市

Tianjin

Tiān Jīn

120000

Municipality

2022

POLYGON ((117.56937 40.19153, 117.56744 40.189...

2

河北省

130000

Hebei

Hé Běi

130000

Province

2022

MULTIPOLYGON (((118.26945 38.98097, 118.26871 ...

3

山西省

140000

Shanxi

Shān Xī

140000

Province

2022

POLYGON ((114.13714 40.73445, 114.13860 40.732...

4

内蒙古自治区

150000

自治区

Neimenggu

Nèi Měng Gǔ

150000

Autonomous Region

2022

POLYGON ((121.49813 53.32607, 121.50116 53.321...

5

辽宁省

210000

Liaoning

Liáo Níng

210000

Province

2022

MULTIPOLYGON (((121.03521 38.87021, 121.03528 ...

6

吉林省

220000

Jilin

Jí Lín

220000

Province

2022

POLYGON ((123.90309 46.29744, 123.90283 46.294...

7

黑龙江省

230000

Heilongjiang

Hēi Lóng Jiāng

230000

Province

2022

POLYGON ((123.40249 53.53506, 123.40471 53.535...

8

上海市

310000

直辖市

Shanghai

Shàng Hǎi

310000

Municipality

2022

MULTIPOLYGON (((121.87476 31.63516, 121.87542 ...

9

浙江省

330000

Zhejiang

Zhè Jiāng

330000

Province

2022

MULTIPOLYGON (((120.47933 27.15321, 120.48163 ...

10

安徽省

340000

Anhui

ān Huī

340000

Province

2022

POLYGON ((116.42485 34.65234, 116.43225 34.642...

11

福建省

350000

Fujian

Fú Jiàn

350000

Province

2022

MULTIPOLYGON (((117.29228 23.59563, 117.29206 ...

12

江西省

360000

Jiangxi

Jiāng Xī

360000

Province

2022

POLYGON ((116.68416 30.07160, 116.68576 30.070...

13

山东省

370000

Shandong

Shān Dōng

370000

Province

2022

MULTIPOLYGON (((119.92414 35.62384, 119.92294 ...

14

河南省

410000

Henan

Hé Nán

410000

Province

2022

MULTIPOLYGON (((111.02770 33.17911, 111.02767 ...

15

湖北省

420000

Hubei

Hú Běi

420000

Province

2022

MULTIPOLYGON (((113.12740 29.43223, 113.11645 ...

16

湖南省

430000

Hunan

Hú Nán

430000

Province

2022

MULTIPOLYGON (((109.47771 26.84005, 109.47793 ...

17

广东省

440000

Guangdong

Guǎng Dōng

440000

Province

2022

MULTIPOLYGON (((110.59023 20.37852, 110.59232 ...

18

广西壮族自治区

450000

自治区

Guangxi

Guǎng Xī

450000

Autonomous Region

2022

MULTIPOLYGON (((109.20674 20.91898, 109.20686 ...

19

海南省

460000

Hainan

Hǎi Nán

460000

Province

2022

MULTIPOLYGON (((112.04381 3.83812, 112.01370 3...

20

重庆市

500000

直辖市

Chongqing

Chóng Qìng

500000

Municipality

2022

POLYGON ((109.57960 31.72849, 109.58644 31.725...

21

四川省

510000

Sichuan

Sì Chuān

510000

Province

2022

POLYGON ((102.95840 34.27996, 102.95933 34.270...

22

贵州省

520000

Guizhou

Guì Zhōu

520000

Province

2022

MULTIPOLYGON (((105.09467 24.92520, 105.09458 ...

23

云南省

530000

Yunnan

Yún Nán

530000

Province

2022

POLYGON ((99.11276 29.21149, 99.11737 29.20723...

24

西藏自治区

540000

自治区

Xizang

Xī Zàng

540000

Autonomous Region

2022

POLYGON ((88.38821 36.47854, 88.38945 36.47845...

25

陕西省

610000

Shaanxi

Shǎn Xī

610000

Province

2022

POLYGON ((108.13454 36.57919, 108.13418 36.580...

26

甘肃省

620000

Gansu

Gān Sù

620000

Province

2022

POLYGON ((97.19051 42.76287, 97.23601 42.67222...

27

青海省

630000

Qinghai

Qīng Hǎi

630000

Province

2022

POLYGON ((100.91694 38.17344, 100.91780 38.173...

28

宁夏回族自治区

640000

自治区

Ningxia

Níng Xià Huí Zú

640000

Autonomous Region

2022

MULTIPOLYGON (((106.06218 35.43728, 106.06239 ...

29

新疆维吾尔自治区

650000

自治区

Xinjiang

Xīn Jiāng

650000

Autonomous Region

2022

POLYGON ((87.79720 49.18060, 87.81916 49.17268...

30

台湾省

710000

Taiwan

Tái Wān

710000

Province

2022

MULTIPOLYGON (((123.69793 25.92930, 123.69726 ...

31

香港特别行政区

810000

特别行政区

HongKong

Hong Kong

810000

Special District

2022

MULTIPOLYGON (((114.22665 22.54375, 114.22661 ...

32

澳门特别行政区

820000

特别行政区

Aomen

ào Mén

820000

Special District

2022

MULTIPOLYGON (((113.55346 22.21547, 113.55374 ...

33

江苏省

320000

Jiangsu

Jiāng Sū

320000

Province

2022

MULTIPOLYGON (((121.56617 32.22928, 121.56693 ...

代码语言:javascript复制
代码语言:javascript复制
# 获取行政区域数据
tj = china_map[china_map['省'] == '天津市']
# 保存裁剪后的tjshp文件
tj.to_file('/home/mw/project/tj.shp')
代码语言:javascript复制
代码语言:javascript复制
---------------------------------------------------------------------------
CPLE_AppDefinedError                      Traceback (most recent call last)
fiona/ogrext.pyx in fiona.ogrext.WritingSession.start()

fiona/_err.pyx in fiona._err.exc_wrap_int()

CPLE_AppDefinedError: Failed to create field name '省': cannot convert to ISO-8859-1

During handling of the above exception, another exception occurred:

SchemaError                               Traceback (most recent call last)
<ipython-input-10-634bcee8b14b> in <module>
      2 tj = china_map[china_map['省'] == '天津市']
      3 # 保存裁剪后的tjshp文件
----> 4 tj.to_file('/home/mw/project/tj.shp')

/opt/conda/lib/python3.9/site-packages/geopandas/geodataframe.py in to_file(self, filename, driver, schema, index, **kwargs)
   1112         from geopandas.io.file import _to_file
   1113 
-> 1114         _to_file(self, filename, driver, schema, index, **kwargs)
   1115 
   1116     def set_crs(self, crs=None, epsg=None, inplace=False, allow_override=False):

/opt/conda/lib/python3.9/site-packages/geopandas/io/file.py in _to_file(df, filename, driver, schema, index, mode, crs, **kwargs)
    391         elif crs:
    392             crs_wkt = crs.to_wkt("WKT1_GDAL")
--> 393         with fiona.open(
    394             filename, mode=mode, driver=driver, crs_wkt=crs_wkt, schema=schema, **kwargs
    395         ) as colxn:

/opt/conda/lib/python3.9/site-packages/fiona/env.py in wrapper(*args, **kwargs)
    406     def wrapper(*args, **kwargs):
    407         if local._env:
--> 408             return f(*args, **kwargs)
    409         else:
    410             if isinstance(args[0], str):

/opt/conda/lib/python3.9/site-packages/fiona/__init__.py in open(fp, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt, **kwargs)
    270             else:
    271                 this_schema = None
--> 272             c = Collection(path, mode, crs=crs, driver=driver, schema=this_schema,
    273                            encoding=encoding, layer=layer, enabled_drivers=enabled_drivers, crs_wkt=crs_wkt,
    274                            **kwargs)

/opt/conda/lib/python3.9/site-packages/fiona/collection.py in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, ignore_fields, ignore_geometry, **kwargs)
    163             elif self.mode in ('a', 'w'):
    164                 self.session = WritingSession()
--> 165                 self.session.start(self, **kwargs)
    166         except IOError:
    167             self.session = None

fiona/ogrext.pyx in fiona.ogrext.WritingSession.start()

SchemaError: Failed to create field name '省': cannot convert to ISO-8859-1

报错原因是由于Fiona库在写入shapefile文件时,遇到了无法转换为ISO-8859-1编码的字符。Shapefile的标准不支持UTF-8编码,因此在处理包含非ISO-8859-1字符(例如中文)的字段时,可能会出现问题。 下面介绍两种方法

方法一:改变列名

代码语言:javascript复制
tj1 = tj.rename(columns={'省': 'Province','省级码':'code','省类型':'type'})
tj1.to_file('/home/mw/project/tj1.shp')
代码语言:javascript复制
shp = gpd.read_file('/home/mw/project/tj1.shp',crs=None)
shp.plot()
plt.show()

好像一只烧鸭

方法二:存取为支持UTF-8编码的GeoJSON格式

代码语言:javascript复制
代码语言:javascript复制
# 获取行政区域数据
tj = china_map[china_map['省'] == '天津市']
tj2.to_file('/home/mw/project/tj2.geojson', driver='GeoJSON')

/opt/conda/lib/python3.9/site-packages/geopandas/io/file.py:362: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
  pd.Int64Index,
# 读取GeoJSON文件
tj2 = gpd.read_file('/home/mw/project/tj2.geojson')
# 绘制GeoDataFrame
tj2.plot()

plt.show()

烧鸭二号完成。可喜可贺。

1 人点赞