Skip to content

Commit f9f343d

Browse files
authored
geopandas: Fix UnicodeEncodeError on Windows for geopandas.GeoDataFrame with non-ASCII characters (#4224)
1 parent 237e7c5 commit f9f343d

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

pygmt/helpers/tempfile.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,12 @@ def tempfile_from_geojson(geojson):
135135
import geopandas as gpd # noqa: PLC0415
136136

137137
Path(tmpfile.name).unlink() # Ensure file is deleted first
138-
ogrgmt_kwargs = {"filename": tmpfile.name, "driver": "OGR_GMT", "mode": "w"}
138+
ogrgmt_kwargs = {
139+
"filename": tmpfile.name,
140+
"driver": "OGR_GMT",
141+
"mode": "w",
142+
"encoding": "UTF-8", # Necessary for non-ASCII support on Windows.
143+
}
139144
try:
140145
# OGR_GMT only supports 32-bit integers. We need to map int/int64
141146
# types to int32/float types depending on if the column has an

pygmt/tests/test_geopandas.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,31 @@ def test_geopandas_data_kind_shapely():
260260
"""
261261
polygon = shapely.geometry.Polygon([(20, 10), (23, 10), (23, 14), (20, 14)])
262262
assert data_kind(data=polygon) == "geojson"
263+
264+
265+
def test_geopandas_nonascii():
266+
"""
267+
Test geopandas.GeoDataFrame with non-ASCII characters.
268+
269+
The tempfile_from_geojson function writes the GeoDataFrame to a temporary OGR_GMT
270+
file, which doesn't work properly if UTF-8 is not the default encoding (e.g.,
271+
Windows).
272+
"""
273+
geom = shapely.geometry.Polygon(
274+
[
275+
(0, 1),
276+
(0, 2),
277+
(1, 1),
278+
(1, 3),
279+
]
280+
)
281+
gdf = gpd.GeoDataFrame(
282+
{
283+
"name_ascii": ["Fiji"],
284+
"name_utf8": ["فيجي"], # Arabic
285+
},
286+
geometry=[geom],
287+
crs="EPSG:4326",
288+
)
289+
output = info(gdf, per_column=True)
290+
npt.assert_allclose(actual=output, desired=[0.0, 1.0, 1.0, 3.0])

0 commit comments

Comments
 (0)