BUG: margins value incorrect with count aggfunc and no index · Issue #58722 · pandas-dev/pandas (original) (raw)

Pandas version checks

Reproducible Example

df = pd.DataFrame({'x': [1, 1, 2], 'y': [3, 3, 4], 'z': [5, 5, 6], 'w': [7, 8, 9]}) print(df.pivot_table(columns=["y", "z"], values="w", margins=True, aggfunc="count"))

y 3 4

z 5 All 6 All

w 2 1 1 1

print(df.pivot_table(index="x", columns=["y", "z"], values="w", margins=True, aggfunc="count"))

y 3 4 All

z 5 6

x

1 2.0 NaN 2

2 NaN 1.0 1

All 2.0 1.0 3

Issue Description

The all column should be a subaggregation over the aggregations, but seems to perhaps be calling count on the result rather than aggregating the counts? E.g., the first result should look like this:

y 3 4

z 5 All 6 All

w 2 2 1 1

Expected Behavior

Values should be aggregations computed over the original data pivoting only on the first pivot column.

Installed Versions

INSTALLED VERSIONS

commit : d9cdd2e
python : 3.11.5.final.0
python-bits : 64
OS : Darwin
OS-release : 23.4.0
Version : Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:49 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6020
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.2.2
numpy : 1.26.4
pytz : 2024.1
dateutil : 2.9.0.post0
setuptools : 68.0.0
pip : 23.2.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 8.22.2
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : 0.19.0
tzdata : 2024.1
qtpy : None
pyqt5 : None