Skip to content

BUG: margin for pivot_table is incorrect with NA column/index values #61509

Open
@vtraag

Description

@vtraag

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

df = pd.DataFrame({"i": [1, 2, 3],
                   "g1": ["a", "b", "b"],
                   "g2": ["x", None, None],
                   })

df.pivot_table(index="g1",
               columns="g2",
               values="i",
               aggfunc="count",
               dropna=False, margins=True)

Issue Description

The margins of a pivot_table are incorrect when the index or columns variables contains missing variables. In particular, for the variable with the missing value, the total is missing.

g1 x nan Total
a 1.0 1
b 2.0 2
All 1.0 3

Expected Behavior

Margins should also be included for columns/indices with missing values.

In particular, the table should look like this

g1 x nan Total
a 1.0 1
b 2.0 2
All 1.0 2.0 3

Installed Versions

INSTALLED VERSIONS

commit : f538741
python : 3.12.8.final.0
python-bits : 64
OS : Linux
OS-release : 6.11.0-26-generic
Version : #26~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Apr 17 19:20:47 UTC 2
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.2.0
numpy : 1.26.4
pytz : 2025.1
dateutil : 2.9.0.post0
setuptools : 75.8.0
pip : 25.0
Cython : None
pytest : None
hypothesis : None
sphinx : 8.1.3
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.5
IPython : 8.22.0
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.13.0
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.9.4
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.4
pandas_gbq : None
pyarrow : 16.1.0
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.14.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : 0.23.0
tzdata : 2025.1
qtpy : 2.4.2
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions