【采样】

  1. 随机选取样本:
1
df.sample(n=6)
  1. 按照百分比随机选取样本
1
df.sample(frac=0.6)
  1. 可复现的随机种子
1
df.sample(n=6,random_state=42)

【地理信息】

创建凸包(Convex)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from shapely.geometry import Polygon,MultiPolygon
# GeoPandas中的geometry继承自shapely.geometry

# 创建一组示例矢量面
polygon1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
polygon2 = Polygon([(1, 0), (2, 0), (2, 1), (1, 1)])
polygon3 = Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])

# 将矢量面合并为一个多边形集合
# 这也是不规则跨空间面要素的存储方式

multi_polygon=MultiPolygon([polygon1,...])

# 对这个多边形集创建凸包
convex_hull=multi_polygon.convex_hull

上面这组示例是介绍从矢量面开始构建凸集,实际上凸集是geometry对象的一个属性,可以直接进行获取。例如在GeoPandas中:

1
df.geometry.convex_hull

合并地理几何体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import geopandas as gpd
from shapely.geometry import Polygon

polygon1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
polygon2 = Polygon([(1, 0), (2, 0), (2, 1), (1, 1)])

gdf=gpd.GeoDataFrame(geometry=[polygon1,polygon2])

# 添加一个列'Group'作为合并的依据
gdf['group']=['Group1','Group1']

# 依据合并key进行几何体合并
merge=gdf.dissolve(by='group')

# 可视化
gdf.plot(edgecolor='black',facecolor='none',linewidth=2)
merge.plot(edgecolor='red',facecolor='none',linewidth=2)

import matplotlib.pyplot as plt
plt.show()

知识点

  • GeoPandas绘制函数
    • df.plot(edgecolor,facecolor,linewith)
  • 创建GDF
    • gpd.GeoDataFrame(geometry=[‘’])
  • 合并对象(重构点集)
    • gpd.dissolve(by=key)

利用Merge方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import geopandas as gpd
from shapely.geometry import Point

# 创建两个示例 GeoDataFrame
data1 = {'ID': [1, 2, 3],
'geometry': [Point(0, 0), Point(1, 1), Point(2, 2)]}
gdf1 = gpd.GeoDataFrame(data1, crs='EPSG:4326')

data2 = {'ID': [2, 3, 4],
'value': [10, 20, 30],
'geometry': [Point(1, 1), Point(2, 2), Point(3, 3)]}
gdf2 = gpd.GeoDataFrame(data2, crs='EPSG:4326')

# 使用 'ID' 列进行合并
merged_gdf = gdf1.merge(gdf2, on='ID',how=inner)

# 输出结果
print(merged_gdf)

知识点

  • 合并
    • gdp_1.merge(gdp_2,on=‘ID’,how=inner)
    • on表示主键,how表示合并方法

空间关系

🌟 包含

1
g.contains()

🌟 相交

1
g.intersects()

创建缓冲区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import geopandas as gpd
from shapely.geometry import Point

# 创建一个示例 GeoDataFrame
data = {'geometry': [Point(0, 0), Point(1, 1), Point(2, 2)]}
gdf = gpd.GeoDataFrame(data)

# 计算质心
gdf['centroid']=gdf['geometry'].centroid
gdf['buffer']=gdf['centroid'].buffer(distance=1.0) # 圆形缓冲区

# 可视化矢量面、质心和缓冲区
ax=gdf.plot(facecolor='none',edgecolor='blue')
gdf['centroid'].plot(ax=ax,color='red',marker='o',markersize=50)
gdf['buffer'].plot(ax=ax,facecolor='none',edgecolor='green',alpha=0.5)

# 显示图形
import matplotlib.pyplot as plt
plt.show()

知识点:

  • 质心
    • geometry.centroid
  • 缓冲区
    • geometry.buffer
  • 在同一图层上绘制
    • 创建图层:ax=gpd.plot()
    • 在图层上绘制:geometry.plot(ax=ax,…)
  • 绘制点
    • point.plot(color,marker,markersize)