ImportError: cannot import name '_gdal_array' from 'osgeo'

Question:

I create a fresh environment, install numpy, then install GDAL. GDAL imports successfully and I can open images using gdal.Open(, but I get the ImportError: cannot import name '_gdal_array' from 'osgeo' error when trying to use ReadAsRaster.

pip list returns:

GDAL       3.6.2
numpy      1.24.2
pip        23.0
setuptools 65.6.3
wheel      0.38.4

Completely stumped, has anyone come across this? Google tells me that installing numpy first is the solution (but that doesn’t help). Help would be much appreciated.

Asked By: jester_thomas

||

Answers:

Pip is most likely caching and reinstalling your bad version of GDAL over and over, even though you installed numpy. Here’s what fixed it for me:

pip3 install --no-cache-dir --force-reinstall 'GDAL[numpy]==3.6.2'

Installing without --no-cache-dir causes pip to reuse the compiled wheel:

% pip3 install --force-reinstall 'GDAL[numpy]==3.6.2'
Collecting GDAL[numpy]==3.6.2
  Using cached GDAL-3.6.2-cp311-cp311-macosx_13_0_x86_64.whl
Collecting numpy>1.0.0
  Using cached numpy-1.24.2-cp311-cp311-macosx_10_9_x86_64.whl (19.8 MB)
Installing collected packages: numpy, GDAL
  Attempting uninstall: numpy
    Found existing installation: numpy 1.24.2
    Uninstalling numpy-1.24.2:
      Successfully uninstalled numpy-1.24.2
  Attempting uninstall: GDAL
    Found existing installation: GDAL 3.6.2
    Uninstalling GDAL-3.6.2:
      Successfully uninstalled GDAL-3.6.2
Successfully installed GDAL-3.6.2 numpy-1.24.2

For others still encountering this issue, make sure wheel is installed.

Pip will download wheel as part of the building process, but it will not work (as of June 2023) and instead blame numpy:

Building wheels for collected packages: GDAL
  Running command Building wheel for GDAL (pyproject.toml)
  WARNING: numpy not available!  Array support will not be enabled
  running bdist_wheel

The only indication that it’s a wheel problem shows up when building without build isolation (--no-build-isolation):

  error: invalid command 'bdist_wheel'
  error: subprocess-exited-with-error
  
  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> See above for output.
Answered By: Will
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.