Skip to content

BUG: pivot_table produces NaT and FutureWarning on dataset with explicitly typed date-value field #43574

Closed
@felciano

Description

@felciano

  • 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 master branch of pandas.

Reproducible Example

import pandas as pd 
import numpy as np

df = pd.DataFrame([
    {'category': 'Books', 'date_str': '2021-01-01', 'amount': 10.00},
    {'category': 'Books', 'date_str': '2021-01-01', 'amount': 20.00},
    {'category': 'Books', 'date_str': '2021-01-03', 'amount': 50.00},
    {'category': 'Vacation', 'date_str': '2021-01-01', 'amount': 100.00},
    {'category': 'Vacation', 'date_str': '2021-01-01', 'amount': 200.00},
    {'category': 'Vacation', 'date_str': '2021-01-02', 'amount': 500.00},
])

df['date'] = pd.to_datetime(df['date_str'])

pivot = df.pivot_table(
    index = ["category", "date"],
    values = ["amount"],
    aggfunc = [np.sum],
    margins = True
)

Issue Description

When executing the pivot_table function with margins=True on a dataset with dates that have been explicitly typed as datetime, a FutureWarning error is produced regarding inference of datetime64[ns], and the pivot operation appears to try to aggregate the date-valued field, producing NaT.

<ipython-input-22-f8a00ede7c0c>:1: FutureWarning: Inferring datetime64[ns] from 
data containing strings is deprecated and will be removed in a future version. To 
retain the old behavior explicitly pass Series(data, dtype={value.dtype})
  pivot = df.pivot_table(

I'm not sure why this warning is triggered given that the date field is explicitly typed (no inference) and fully populated (no missing date values).

Here's what the pivot produces, with the NaT on the bottom row under the date column:

                       sum
                    amount
category date             
Books    2021-01-01   30.0
         2021-01-03   50.0
Vacation 2021-01-01  300.0
         2021-01-02  500.0
All      NaT         880.0

Expected Behavior

Absent a clear semantic for summing up date-valued fields, I would expect the pivot operation to ignore that field when calculating totals as part of the margins behavior, and no FutureWarning to be produced.

The expected resulting table would look like (note absent 'NaTon the bottomAll` line):

                       sum
                    amount
category date             
Books    2021-01-01   30.0
         2021-01-03   50.0
Vacation 2021-01-01  300.0
         2021-01-02  500.0
All                  880.0

Installed Versions

INSTALLED VERSIONS

commit : 73c6825
python : 3.8.11.final.0
python-bits : 64
OS : Darwin
OS-release : 20.6.0
Version : Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.3
numpy : 1.19.2
pytz : 2020.1
dateutil : 2.8.1
pip : 21.1.2
setuptools : 57.0.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 1.3.6
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.18.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.2
numexpr : None
odfpy : None
openpyxl : 3.0.5
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : 1.3.19
tables : None
tabulate : None
xarray : None
xlrd : 1.2.0
xlwt : 1.3.0
numba : None

Metadata

Metadata

Assignees

Labels

BugMissing-datanp.nan, pd.NaT, pd.NA, dropna, isnull, interpolateNeeds DiscussionRequires discussion from core team before further actionNeeds TestsUnit test(s) needed to prevent regressionsReshapingConcat, Merge/Join, Stack/Unstack, ExplodeWarningsWarnings that appear or should be added to pandas

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions