Skip to content

Commit 84e7d1a

Browse files
authored
BUG: allow kwargs in Styler apply_index and map_index (#1725)
* BUG: allow kwargs in Styler apply_index and map_index * fixup! BUG: allow kwargs in Styler apply_index and map_index
1 parent 82c9851 commit 84e7d1a

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

pandas-stubs/io/formats/style.pyi

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ class _SeriesFunc(Protocol):
5757
self, series: Series, /, *args: Any, **kwargs: Any
5858
) -> list[Any] | Series: ...
5959

60+
class _SeriesStrFunc(Protocol):
61+
def __call__(
62+
self, series: Series[str], /, *args: Any, **kwargs: Any
63+
) -> list[str] | Series[str]: ...
64+
6065
class _DataFrameFunc(Protocol):
6166
def __call__(
6267
self, series: DataFrame, /, *args: Any, **kwargs: Any
@@ -277,14 +282,17 @@ class Styler(StylerRenderer):
277282
) -> Styler: ...
278283
def apply_index(
279284
self,
280-
func: Callable[[Series], list[str] | np_ndarray_str | Series[str]],
285+
func: (
286+
_SeriesStrFunc
287+
| Callable[[Series], list[str] | np_ndarray_str | Series[str]]
288+
),
281289
axis: Axis = ...,
282290
level: Level | list[Level] | None = ...,
283291
**kwargs: Any,
284292
) -> Styler: ...
285293
def map_index(
286294
self,
287-
func: Callable[[Scalar], str | None],
295+
func: _MapCallable | Callable[[Scalar], str | None],
288296
axis: Axis = ...,
289297
level: Level | list[Level] | None = ...,
290298
**kwargs: Any,

tests/test_styler.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,29 @@ def f1(s: Series) -> Series[str]:
7676

7777
check(assert_type(DF.style.apply_index(f1), Styler), Styler)
7878

79+
# GH 1723
80+
def highlight_odd(index: pd.Series, color: str) -> list[str]:
81+
return [f"color: {color}" if x % 2 else "" for x in index]
82+
83+
check(
84+
assert_type(
85+
DF.style.apply_index(highlight_odd, axis=0, color="purple"), Styler
86+
),
87+
Styler,
88+
)
89+
7990

8091
def test_map_index() -> None:
8192
def f(s: Scalar) -> str | None:
8293
return "background-color: yellow;" if s == "B" else None
8394

8495
check(assert_type(DF.style.map_index(f), Styler), Styler)
8596

97+
def f1(s: Scalar, color: str) -> str | None:
98+
return f"background-color: {color};" if s == "b" else None
99+
100+
check(assert_type(DF.style.map_index(f1, color="pink", axis=0), Styler), Styler)
101+
86102

87103
def test_background_gradient() -> None:
88104
check(assert_type(DF.style.background_gradient(), Styler), Styler)

0 commit comments

Comments
 (0)