Skip to content

Commit 98ea838

Browse files
pfebrerzerothi
andauthored
Fix plots bug due to new pandas casting (#983)
* Fix plots bug due to new pandas casting * refactor of code for older pandas versions --------- Co-authored-by: Nick Papior <nickpapior@gmail.com>
1 parent ac11f9e commit 98ea838

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

changes/983.fix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
bug fix for pandas >= 3 migration

src/sisl/viz/plotters/xarray.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,48 @@
88
from typing import Literal, Optional, Union
99

1010
import numpy as np
11+
import pandas as pd
1112
from xarray import DataArray, Dataset
1213

1314
from . import plot_actions
1415

1516
# from sisl.viz.nodes.processors.grid import get_isos
1617

1718

19+
def _correct_pandas_string_none(dic: dict[str, DataArray]):
20+
"""Correct string arguments in xarray arrays to avoid casting to nan
21+
22+
This is a migration notice from pandas >= 3.
23+
They change their str implementation to a custom (new default) dtype.
24+
And the result is that `None` will be parsed to `np.nan` as opposed
25+
to the old `None -> None` parsing.
26+
"""
27+
28+
# xarray uses pandas for casting types, and pandas decided to change
29+
# the default behavior and parse [None, ""], to [nan, ""]. Passing
30+
# NaN to plotting functions when they are expecting None breaks things.
31+
# Here we make sure that we parse all NaN to None
32+
# Pandas docs on this:
33+
# https://pandas.pydata.org/docs/user_guide/migration-3-strings.html
34+
old_infer_string = pd.options.future.infer_string
35+
pd.options.future.infer_string = False
36+
37+
for key, value in dic.items():
38+
value = dic[key]
39+
try:
40+
dic[key] = value.where(value.notnull(), other=None)
41+
except:
42+
pass
43+
44+
pd.options.future.infer_string = old_infer_string
45+
46+
47+
if int(pd.__version__.split(".")[0]) >= 3:
48+
49+
def _correct_pandas_string_none(dic: dict[str, str]):
50+
pass
51+
52+
1853
def _process_xarray_data(
1954
data: Union[DataArray, Dataset],
2055
x: Union[str, None] = None,
@@ -461,6 +496,8 @@ def _draw_xarray_lines(
461496
"border_width",
462497
"border_color",
463498
)
499+
_correct_pandas_string_none(style)
500+
464501
for key in style_keys:
465502
lines_style[key] = style.get(key)
466503

0 commit comments

Comments
 (0)