Skip to content

Commit ef5f01a

Browse files
committed
Call .map() if pandas version is 2.1.0 or greater
1 parent d7d53ec commit ef5f01a

File tree

4 files changed

+55
-16
lines changed

4 files changed

+55
-16
lines changed

src/estimagic/config.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
from pathlib import Path
2+
import pandas as pd
3+
from packaging import version
24

35
import plotly.express as px
46

@@ -19,9 +21,9 @@
1921
CRITERION_PENALTY_SLOPE = 0.1
2022
CRITERION_PENALTY_CONSTANT = 100
2123

22-
# =====================================================================================
24+
# ======================================================================================
2325
# Check Available Packages
24-
# =====================================================================================
26+
# ======================================================================================
2527

2628
try:
2729
from petsc4py import PETSc # noqa: F401
@@ -103,9 +105,18 @@
103105
IS_NUMBA_INSTALLED = True
104106

105107

106-
# =================================================================================
108+
# ======================================================================================
109+
# Check if pandas version is newer or equal to version 2.1.0
110+
# ======================================================================================
111+
112+
IS_PANDAS_VERSION_NEWER_OR_EQUAL_TO_2_1_0 = version.parse(
113+
pd.__version__
114+
) >= version.parse("2.1.0")
115+
116+
117+
# ======================================================================================
107118
# Dashboard Defaults
108-
# =================================================================================
119+
# ======================================================================================
109120

110121
Y_RANGE_PADDING = 0.05
111122
Y_RANGE_PADDING_UNITS = "absolute"

src/estimagic/optimization/optimize_result.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import numpy as np
55
import pandas as pd
66

7-
from estimagic.utilities import to_pickle
7+
from estimagic.utilities import to_pickle, pandas_df_map
88

99

1010
@dataclass
@@ -128,7 +128,7 @@ def _format_convergence_report(report, algorithm):
128128
report = pd.DataFrame.from_dict(report)
129129
columns = ["one_step", "five_steps"]
130130

131-
table = report[columns].applymap(_format_float).astype(str)
131+
table = pandas_df_map(report[columns], _format_float).astype(str)
132132

133133
for col in "one_step", "five_steps":
134134
table[col] = table[col] + _create_stars(report[col])

src/estimagic/utilities.py

+26
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import numpy as np
77
import pandas as pd
88
from scipy.linalg import ldl, qr
9+
from estimagic.config import IS_PANDAS_VERSION_NEWER_OR_EQUAL_TO_2_1_0
910

1011
with warnings.catch_warnings():
1112
warnings.simplefilter("ignore", category=UserWarning)
@@ -321,3 +322,28 @@ def get_rng(seed):
321322
else:
322323
raise TypeError("seed type must be in {None, int, numpy.random.Generator}.")
323324
return rng
325+
326+
327+
def pandas_df_map(df, func, na_action=None, **kwargs):
328+
"""Apply a function to a Dataframe elementwise.
329+
330+
pandas has depricated the .applymap() function with version 2.1.0. This function
331+
calls either .map() (if pandas version is greater or equal to 2.1.0) or .applymap()
332+
(if pandas version is smaller than 2.1.0).
333+
334+
Args:
335+
df (pd.DataFrame): A pandas DataFrame.
336+
func (callable): Python function, returns a single value from a single value.
337+
na_action (str): If 'ignore', propagate NaN values, without passing them to
338+
func. If None, pass NaN values to func. Default is None.
339+
**kwargs: Additional keyword arguments to pass as keywords arguments to func.
340+
341+
Returns:
342+
pd.DataFrame: Transformed DataFrame.
343+
344+
"""
345+
if IS_PANDAS_VERSION_NEWER_OR_EQUAL_TO_2_1_0:
346+
out = df.map(func, na_action=na_action, **kwargs)
347+
else:
348+
out = df.applymap(func, na_action=na_action, **kwargs)
349+
return out

src/estimagic/visualization/estimation_table.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from functools import partial
44
from pathlib import Path
55
from warnings import warn
6+
from estimagic.utilities import pandas_df_map
67

78
import numpy as np
89
import pandas as pd
@@ -305,7 +306,7 @@ def render_latex(
305306
ci_in_body = False
306307

307308
if ci_in_body:
308-
body.loc[("",)] = body.loc[("",)].applymap("{{{}}}".format).values
309+
body.loc[("",)] = pandas_df_map(body.loc[("",)], "{{{}}}".format).values
309310
if body.columns.nlevels > 1:
310311
column_groups = body.columns.get_level_values(0)
311312
else:
@@ -1383,22 +1384,23 @@ def _apply_number_format(df_raw, number_format, format_integers):
13831384
if isinstance(processed_format, (list, tuple)):
13841385
df_formatted = df_raw.copy(deep=True).astype("float")
13851386
for formatter in processed_format[:-1]:
1386-
df_formatted = df_formatted.applymap(formatter.format).astype("float")
1387-
df_formatted = df_formatted.astype("float").applymap(
1388-
processed_format[-1].format
1387+
df_formatted = pandas_df_map(df_formatted, formatter.format).astype("float")
1388+
df_formatted = pandas_df_map(
1389+
df_formatted.astype("float"), processed_format[-1].format
13891390
)
13901391
elif isinstance(processed_format, str):
1391-
df_formatted = df_raw.astype("str").applymap(
1392-
partial(_format_non_scientific_numbers, format_string=processed_format)
1392+
df_formatted = pandas_df_map(
1393+
df_raw.astype("str"),
1394+
partial(_format_non_scientific_numbers, format_string=processed_format),
13931395
)
13941396
elif callable(processed_format):
1395-
df_formatted = df_raw.applymap(processed_format)
1397+
df_formatted = pandas_df_map(df_raw, processed_format)
13961398

13971399
# Don't format integers: set to original value
13981400
if not format_integers:
1399-
integer_locs = df_raw.applymap(_is_integer)
1400-
df_formatted[integer_locs] = (
1401-
df_raw[integer_locs].astype(float).applymap("{:.0f}".format)
1401+
integer_locs = pandas_df_map(df_raw, _is_integer)
1402+
df_formatted[integer_locs] = pandas_df_map(
1403+
df_raw[integer_locs].astype(float), "{:.0f}".format
14021404
)
14031405
return df_formatted
14041406

0 commit comments

Comments
 (0)