Skip to content

Commit

Permalink
[MNT] handle deprecation of pandas.DataFrame.applymap (#170)
Browse files Browse the repository at this point in the history
This PR handles deprecation of `DataFrame.applymap`, by replacing
instances with a version-conditional call.

Additionally, also fixes a minor, unrelated docstring typo.
  • Loading branch information
fkiraly committed Jan 7, 2024
1 parent 4aa822c commit 7bf433b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 10 deletions.
12 changes: 4 additions & 8 deletions skpro/distributions/base.py
Expand Up @@ -11,6 +11,7 @@
import pandas as pd

from skpro.base import BaseObject
from skpro.utils.pandas import df_map
from skpro.utils.validation._dependencies import _check_estimator_deps


Expand Down Expand Up @@ -229,7 +230,8 @@ def pdf(self, x):
"this may be numerically unstable"
)
warn(self._method_error_msg("pdf", fill_in=approx_method))
return self.log_pdf(x=x).applymap(np.exp)

return df_map(self.log_pdf(x=x))(np.exp)

raise NotImplementedError(self._method_error_msg("pdf", "error"))

Expand Down Expand Up @@ -269,13 +271,7 @@ def log_pdf(self, x):
)
warn(self._method_error_msg("log_pdf", fill_in=approx_method))

pdf_res = self.pdf(x=x)
# safe deprecation of applymap, renamed to map in pandas 2 versions
# this if/else ensures compatibility with a wider range of pandas versions
if hasattr(pdf_res, "map"):
return pdf_res.map(np.log)
else:
return pdf_res.applymap(np.log)
return df_map(self.pdf(x=x))(np.log)

raise NotImplementedError(self._method_error_msg("log_pdf", "error"))

Expand Down
4 changes: 2 additions & 2 deletions skpro/distributions/normal.py
Expand Up @@ -15,9 +15,9 @@ class Normal(BaseDistribution):
Parameters
----------
mean : float or array of float (1D or 2D)
mu : float or array of float (1D or 2D)
mean of the normal distribution
sd : float or array of float (1D or 2D), must be positive
sigma : float or array of float (1D or 2D), must be positive
standard deviation of the normal distribution
index : pd.Index, optional, default = RangeIndex
columns : pd.Index, optional, default = RangeIndex
Expand Down
26 changes: 26 additions & 0 deletions skpro/utils/pandas.py
@@ -0,0 +1,26 @@
#!/usr/bin/env python3 -u
"""Utilities for pandas adapbation."""

__author__ = ["fkiraly"]


def df_map(x):
"""Access map or applymap, of DataFrame.
In pandas 2.1.0, applymap was deprecated in favor of the newly introduced map.
To ensure compatibility with older versions, we use map if available,
otherwise applymap.
Parameters
----------
x : assumed pd.DataFrame
Returns
-------
x.map, if available, otherwise x.applymap
Note: returns method itself, not result of method call
"""
if hasattr(x, "map"):
return x.map
else:
return x.applymap

0 comments on commit 7bf433b

Please sign in to comment.