Skip to content

Commit 75b2812

Browse files
GH1226 Add Styler.map to the stubs (#1228)
* GH1226 Add Styler.map to the stubs * Update pandas-stubs/io/formats/style.pyi Co-authored-by: Irv Lustig <irv@princeton.com> * GH1226 PR Feedback * GH1226 PR Feedback * GH1226 PR Feedback * GH1226 PR Feedback * GH1226 PR Feedback --------- Co-authored-by: Irv Lustig <irv@princeton.com>
1 parent 5686ca9 commit 75b2812

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

‎pandas-stubs/io/formats/style.pyi

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ class _DataFrameFunc(Protocol):
5353
self, series: DataFrame, /, *args: Any, **kwargs: Any
5454
) -> npt.NDArray | DataFrame: ...
5555

56+
class _MapCallable(Protocol):
57+
def __call__(
58+
self, first_arg: Scalar, /, *args: Any, **kwargs: Any
59+
) -> str | None: ...
60+
5661
class Styler(StylerRenderer):
5762
def __init__(
5863
self,
@@ -71,6 +76,19 @@ class Styler(StylerRenderer):
7176
formatter: ExtFormatter | None = ...,
7277
) -> None: ...
7378
def concat(self, other: Styler) -> Styler: ...
79+
@overload
80+
def map(
81+
self,
82+
func: Callable[[Scalar], str | None],
83+
subset: Subset | None = ...,
84+
) -> Styler: ...
85+
@overload
86+
def map(
87+
self,
88+
func: _MapCallable,
89+
subset: Subset | None = ...,
90+
**kwargs: Any,
91+
) -> Styler: ...
7492
def set_tooltips(
7593
self,
7694
ttips: DataFrame,

‎tests/test_styler.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030

3131
DF = DataFrame({"a": [1, 2, 3], "b": [3.14, 2.72, 1.61]})
3232

33-
3433
PWD = pathlib.Path(os.path.split(os.path.abspath(__file__))[0])
3534

3635
if TYPE_CHECKING:
@@ -233,3 +232,30 @@ def test_styler_columns_and_index() -> None:
233232
styler = DF.style
234233
check(assert_type(styler.columns, Index), Index)
235234
check(assert_type(styler.index, Index), Index)
235+
236+
237+
def test_styler_map() -> None:
238+
"""Test type returned with Styler.map GH1226."""
239+
df = DataFrame(data={"col1": [1, -2], "col2": [-3, 4]})
240+
check(
241+
assert_type(
242+
df.style.map(
243+
lambda v: "color: red;" if isinstance(v, float) and v < 0 else None
244+
),
245+
Styler,
246+
),
247+
Styler,
248+
)
249+
250+
def color_negative(v: Scalar, /, color: str) -> str | None:
251+
return f"color: {color};" if isinstance(v, float) and v < 0 else None
252+
253+
df = DataFrame(np.random.randn(5, 2), columns=["A", "B"])
254+
255+
check(
256+
assert_type(
257+
df.style.map(color_negative, color="red"),
258+
Styler,
259+
),
260+
Styler,
261+
)

0 commit comments

Comments
 (0)