Skip to content

Commit 159747d

Browse files
committed
Add Styler.pipe() method, akin to DataFrame.pipe()
1 parent dae17ab commit 159747d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

pandas/io/formats/style.py

+29
Original file line numberDiff line numberDiff line change
@@ -1222,6 +1222,35 @@ class MyStyler(cls):
12221222

12231223
return MyStyler
12241224

1225+
def pipe(self, func, *args, **kwargs):
1226+
"""
1227+
Apply func(self, *args, **kwargs)
1228+
1229+
Parameters
1230+
----------
1231+
func : function
1232+
function to apply to the Styler.
1233+
``args``, and ``kwargs`` are passed into ``func``.
1234+
Alternatively a ``(callable, data_keyword)`` tuple where
1235+
``data_keyword`` is a string indicating the keyword of
1236+
``callable`` that expects the Styler.
1237+
args : iterable, optional
1238+
positional arguments passed into ``func``.
1239+
kwargs : mapping, optional
1240+
a dictionary of keyword arguments passed into ``func``.
1241+
1242+
Returns
1243+
-------
1244+
result : the value returned by ``func``.
1245+
1246+
See Also
1247+
--------
1248+
Styler.apply
1249+
Styler.applymap
1250+
pandas.DataFrame.pipe
1251+
"""
1252+
return com._pipe(self, func, *args, **kwargs)
1253+
12251254

12261255
def _is_visible(idx_row, idx_col, lengths):
12271256
"""

pandas/tests/io/formats/test_style.py

+18
Original file line numberDiff line numberDiff line change
@@ -1173,6 +1173,24 @@ def test_hide_columns_mult_levels(self):
11731173
assert ctx['body'][1][2]['is_visible']
11741174
assert ctx['body'][1][2]['display_value'] == 3
11751175

1176+
def test_pipe(self):
1177+
def set_caption_from_template(styler, a, b):
1178+
return styler.set_caption(
1179+
'Dataframe with a = {a} and b = {b}'.format(a=a, b=b))
1180+
styler = self.df.style.pipe(set_caption_from_template, 'A', b='B')
1181+
assert 'Dataframe with a = A and b = B' in styler.render()
1182+
1183+
def f(s, *args, **kwargs):
1184+
return s, args, kwargs
1185+
1186+
result = self.df.style.pipe(f, 0, a=1)
1187+
assert result[1] == (0,)
1188+
assert result[2] == dict(a=1)
1189+
1190+
def g(*, styler=None):
1191+
return styler.data
1192+
assert self.df.style.pipe((g, 'styler')) is self.df
1193+
11761194

11771195
@td.skip_if_no_mpl
11781196
class TestStylerMatplotlibDep(object):

0 commit comments

Comments
 (0)