Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
2 of 3 tasks
felciano opened this issue Sep 14, 2021 · 5 comments · Fixed by #54360
Closed
2 of 3 tasks
Assignees
Labels
Bug Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Needs Discussion Requires discussion from core team before further action Needs Tests Unit test(s) needed to prevent regressions Reshaping Concat, Merge/Join, Stack/Unstack, Explode Warnings Warnings that appear or should be added to pandas

Comments

@felciano
Copy link

  • 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

@felciano felciano added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 14, 2021
@mroeschke mroeschke added Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Needs Discussion Requires discussion from core team before further action Reshaping Concat, Merge/Join, Stack/Unstack, Explode Warnings Warnings that appear or should be added to pandas and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 30, 2021
@felciano
Copy link
Author

felciano commented Oct 2, 2021

Hi @mroeschke thanks for reviewing this bug. Can you clarify the missing-data tag? Is there additional information I should have provided in the bug report itself?

@mroeschke
Copy link
Member

missing-data refers to "null data and null data operations" in the issue tracker, so nothing lacking on your end. Thank you for a clear and concise bug report!

@VasylKolomiiets
Copy link

May be it is obviously, but better to say )

variant with last row pivoting like this

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

rise the same warning:

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=datetime64[ns])
pivot = pd.pivot_table(df,

@jbrockmendel
Copy link
Member

The output now matches what the user expects in the OP. Could use a test (or determine if one already exists)

@jbrockmendel jbrockmendel added the Needs Tests Unit test(s) needed to prevent regressions label Mar 28, 2023
@kvn4
Copy link
Contributor

kvn4 commented Jul 31, 2023

take

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Needs Discussion Requires discussion from core team before further action Needs Tests Unit test(s) needed to prevent regressions Reshaping Concat, Merge/Join, Stack/Unstack, Explode Warnings Warnings that appear or should be added to pandas
Projects
None yet
5 participants