如何将Pandas质心序列转换为可在Geopandas中映射的点?
解决GeoPandas绘制质心时的"TypeError: no numeric data to plot"问题
问题出在你当前的Centroid列存储的是字典格式数据,GeoPandas无法直接将其识别为可绘制的几何对象,因此调用plot()时触发报错。
解决步骤:
- 从字典中提取坐标,转换为Shapely的
Point对象 - 将
Point对象设为GeoDataFrame的geometry列 - 指定正确的坐标系(你的数据SRID为4326,对应WGS84)
完整代码示例:
import pandas as pd import geopandas as gpd from shapely.geometry import Point import matplotlib.pyplot as plt # 处理质心数据,转换为Point对象 def convert_to_point(centroid_dict): lon, lat = centroid_dict['Geometry'] return Point(lon, lat) # 创建新的GeoDataFrame mi_sources_centroids = gpd.GeoDataFrame() # 应用转换函数生成geometry列 mi_sources_centroids['geometry'] = mi_sources_gdf['Centroid'].apply(convert_to_point) # 设置坐标系 mi_sources_centroids.set_crs(epsg=4326, inplace=True) # 绘图(可叠加密歇根底图) fig, ax = plt.subplots(figsize=(13,13)) # 绘制底图(替换为你的底图GeoDataFrame变量名) mi_base_map.plot(ax=ax, color='lightgray', edgecolor='white') # 绘制质心点 mi_sources_centroids.plot(ax=ax, color="red", markersize=6) plt.show()
补充说明:
如果你的Centroid列是字符串格式的字典(而非原生字典),需要先将字符串转为字典,可使用ast.literal_eval:
import ast mi_sources_gdf['Centroid'] = mi_sources_gdf['Centroid'].apply(ast.literal_eval)
确保已安装shapely库,未安装可执行:
pip install shapely
内容的提问来源于stack exchange,提问作者Julie Mitchell
相关产品推荐
相关产品推荐

