PyCharm中无法安装contextily模块的问题求助
解决Windows下安装contextily时的GDAL编译错误
问题重现
运行NetworkX地理空间示例代码:
from libpysal import weights, examples from contextily import add_basemap import matplotlib.pyplot as plt import networkx as nx import numpy as np import geopandas cases = geopandas.read_file("cholera_cases.gpkg") coordinates = np.column_stack((cases.geometry.x, cases.geometry.y)) knn3 = weights.KNN.from_dataframe(cases, k=3) dist = weights.DistanceBand.from_array(coordinates, threshold=50) knn_graph = knn3.to_networkx() dist_graph = dist.to_networkx() positions = dict(zip(knn_graph.nodes, coordinates)) f, ax = plt.subplots(1, 2, figsize=(8, 4)) for i, facet in enumerate(ax): cases.plot(marker=".", color="orangered", ax=facet) add_basemap(facet) facet.set_title(("KNN-3", "50-meter Distance Band")[i]) facet.axis("off") nx.draw(knn_graph, positions, ax=ax[0], node_size=5, node_color="b") nx.draw(dist_graph, positions, ax=ax[1], node_size=5, node_color="b") plt.show()
首次运行报错:
Traceback (most recent call last): File "...my.path...", line 14, in <module> from contextily import add_basemap ModuleNotFoundError: No module named 'contextily'
执行pip install contextily时触发依赖安装错误:
... Collecting rasterio Using cached rasterio-1.2.10.tar.gz (2.3 MB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [2 lines of output] INFO:root:Building on Windows requires extra options to setup.py to locate needed GDAL files. More information is available in the README. ERROR: A GDAL API version must be specified. Provide a path to gdal-config using a GDAL_CONFIG environment variable or use a GDAL_VERSION environment variable. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip.
解决方案
方法1:用conda安装(推荐,Windows环境最省心)
Windows下pip编译GDAL依赖容易出问题,conda提供预编译的二进制包,直接执行:
- 打开PyCharm终端或Anaconda Prompt,激活你的Python环境
- 运行命令:
conda install -c conda-forge contextily
该命令会自动安装contextily及其所有依赖(包括GDAL、rasterio等),无需手动处理编译问题。
方法2:安装预编译的whl包
如果不想用conda,可以下载对应Python版本和系统位数的预编译whl文件:
- 下载GDAL和rasterio的whl文件(匹配你的Python版本和Windows位数)
- 先安装GDAL:
pip install GDAL-<版本号>-cp<Python版本>-cp<Python版本>-win_amd64.whl
- 再安装rasterio:
pip install rasterio-<版本号>-cp<Python版本>-cp<Python版本>-win_amd64.whl
- 最后安装contextily:
pip install contextily
方法3:临时跳过底图功能(快速验证代码)
如果只是想测试NetworkX的图生成逻辑,不需要底图,可以修改代码:
- 注释掉
from contextily import add_basemap - 注释掉循环里的
add_basemap(facet)
修改后的代码可以正常运行,跳过contextily的依赖。
内容的提问来源于stack exchange,提问作者hellomynameisA
相关产品推荐
相关产品推荐

