Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
test = pd.DataFrame({"A": [1, 2, 3]}, index=["I1", "I2", "I3"])
indexer = lambda df: df.index=="I2"
print(test.loc[indexer])
# A
# I2 2
test.style.format(lambda x: f"{x:0.3f}", subset=indexer).to_html()
# KeyError: "None of [Index([<function <lambda> at 0x00000________>], dtype='object')] are in the [index]"
Issue Description
The .loc
documentation states that a callable function is an allowable input. Styler documentation implies that subset accepts any valid loc input:
A valid 2d input to DataFrame.loc[<subset>], or, in the case of a 1d input or single key, to DataFrame.loc[:, <subset>] where the columns are prioritised, to limit data to before applying the function.
When a callable is passed to the subset
argument in styler methods, it raises a KeyError
. The root cause is the _non_reducing_slice
function does not properly handling callable subsets.
Expected Behavior
The format function is applied correctly to the "I2" index only.
<style type="text/css">\n</style>\n<table id="T_163a1">\n <thead>\n <tr>\n <th class="blank level0" > </th>\n <th id="T_163a1_level0_col0" class="col_heading level0 col0" >A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th id="T_163a1_level0_row0" class="row_heading level0 row0" >I1</th>\n <td id="T_163a1_row0_col0" class="data row0 col0" >1</td>\n </tr>\n <tr>\n <th id="T_163a1_level0_row1" class="row_heading level0 row1" >I2</th>\n <td id="T_163a1_row1_col0" class="data row1 col0" >2.000</td>\n </tr>\n <tr>\n <th id="T_163a1_level0_row2" class="row_heading level0 row2" >I3</th>\n <td id="T_163a1_row2_col0" class="data row2 col0" >3</td>\n </tr>\n </tbody>\n</table>\n
Installed Versions
INSTALLED VERSIONS
commit : 06d2301
python : 3.10.1.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version :
machine : AMD64
processor :
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 1.4.1
numpy : 1.22.0
pytz : 2021.3
dateutil : 2.8.2
pip : 22.0.4
setuptools : 60.2.0
Cython : None
pytest : 7.0.1
hypothesis : None
sphinx : 3.5.4
blosc : None
feather : None
xlsxwriter : 3.0.2
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.3
IPython : 8.0.0
pandas_datareader: None
bs4 : 4.10.0
bottleneck : 1.3.2
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.5.1
numba : None
numexpr : 2.8.0
odfpy : None
openpyxl : 3.0.9
pandas_gbq : None
pyarrow : None
pyreadstat : 1.1.4
pyxlsb : None
s3fs : None
scipy : 1.7.3
sqlalchemy : 1.4.32
tables : 3.6.1
tabulate : None
xarray : None
xlrd : 2.0.1
xlwt : None
zstandard : None