Skip to content

BUG: highlight_min and highlight_max do not work with pd.NA #42750

Closed
@cynddl

Description

@cynddl
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

import pandas as pd
import numpy as np

df_ok = pd.DataFrame(dict(a=[np.nan, -1, 1], b=[np.nan, -1, 1]))
df_bug = pd.DataFrame(dict(a=[pd.NA, -1, 1], b=[pd.NA, -1, 1]))

Problem description

df_ok.style.highlight_min() works correctly while df_bug.style.highlight_min() returns the following error:

TypeError: boolean value of NA is ambiguous

Fix

For highlight_min, the error comes from https://github.com/pandas-dev/pandas/blob/v1.3.1/pandas/io/formats/style.py#L2367. Specifically, from the following line:

np.where(data == np.nanmin(data.to_numpy()), props, "")

I'm assuming this could be fixed by replacing it with:

np.where(data == data.min(skipna=True), props, "")

or by making sure to_numpy converts pd.NA to np.nan?

Happy to implement a fix.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : c7f7443
python : 3.8.3.final.0
python-bits : 64
OS : Darwin
OS-release : 20.4.0
Version : Darwin Kernel Version 20.4.0: Thu Apr 22 21:46:47 PDT 2021; root:xnu-7195.101.2~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : en_US.UTF-8
LANG : en_GB.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.1
numpy : 1.19.2
pytz : 2021.1
dateutil : 2.8.1
pip : 20.0.2
setuptools : 52.0.0.post20210125
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.3
IPython : 7.20.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.4.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.6.2
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugMissing-datanp.nan, pd.NaT, pd.NA, dropna, isnull, interpolateRegressionFunctionality that used to work in a prior pandas versionStylerconditional formatting using DataFrame.style

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions