DataFrame.style.applymap: subset kwarg fails with MultiIndexSlice · Issue #19861 · pandas-dev/pandas (original) (raw)

Code Sample, a copy-pastable example if possible

import pandas as pd

def color_negative_red(val): """ Takes a scalar and returns a string with the css property 'color: red' for negative strings, black otherwise. """ color = 'red' if val < 0 else 'black' return 'color: %s' % color

dic = {('a', 'd'): [-1.12, 2.11], ('a', 'c'): [2.78, -2.88], ('b', 'c'): [-3.99, 3.77], ('b', 'd'): [4.21, -1.22], }

idx = pd.IndexSlice df = pd.DataFrame(dic, index=[0, 1])

html = ( df.style # .applymap(color_negative_red) .applymap(color_negative_red, subset=idx[:, idx['b', 'd']]) .render() )

Problem description

The subset keyword argument does not work with a MultiIndex IndexSlice. The relevant documentation says "For row and column slicing, any valid indexer to .loc will work" (source).

Actual Output

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 434, in render
    self._compute()
  File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 502, in _compute
    r = func(self)(*args, **kwargs)
  File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 591, in _applymap
    result = self.data.loc[subset].applymap(func)
  File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\core\generic.py", line 3081, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'applymap'

Expected Output

color_negative_red applied to the cell(s) corresponding to the MultiIndex IndexSlice.

Output of pd.show_versions()

[paste the output of pd.show_versions() here below this line]

INSTALLED VERSIONS

commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None
pandas: 0.22.0
pytest: 3.3.2
pip: 9.0.1
setuptools: 38.4.0
Cython: None
numpy: 1.14.0
scipy: 1.0.0
pyarrow: 0.8.0
xarray: None
IPython: None
sphinx: 1.6.6
patsy: None
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: 0.4.0
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None