BUG: `FutureWarning: Inferring datetime64[ns]` when using `pd.pivot_table(..., margins=True)` and `datetime64[ns]`

This issue has been created since 2022-09-21.

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
import numpy as np

df = pd.DataFrame(
    {
        "state": ["CA", "WA", "CO", "AZ"] * 3,
        "office_id": list(range(1, 7)) * 2,
        "date": [pd.Timestamp.now().date() - pd.Timedelta(days=d) for d in range(6)] * 2,
        "sales": [np.random.randint(100_000, 999_999) for _ in range(12)]
    }
).astype(
    {
        "sales": np.float64,
        "date": pd.api.types.pandas_dtype("datetime64[ns]")
    }
)

df.pivot_table(index=["office_id", "date"], columns="state", margins=True, aggfunc="sum")

Issue Description

Following on from this issue, when the .dtype of a column in the aggregation is datetime64[ns] a warning is emitted. The warning is not emitted when using the non-Pandas native dtype.

Expected Behavior

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "state": ["CA", "WA", "CO", "AZ"] * 3,
        "office_id": list(range(1, 7)) * 2,
        "date": [pd.Timestamp.now().date() - pd.Timedelta(days=d) for d in range(6)] * 2,
        "sales": [np.random.randint(100_000, 999_999) for _ in range(12)]
    }
).astype(
    {
        "sales": np.float64,
        "date": pd.api.types.pandas_dtype("O") # works, no warning
    }
)

df.pivot_table(index=["office_id", "date"], columns="state", margins=True, aggfunc="sum")

Installed Versions

INSTALLED VERSIONS

commit : 87cfe4e
python : 3.10.4.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19044
machine : AMD64
processor : Intel64 Family 6 Model 165 Stepping 3, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United Kingdom.1252

pandas : 1.5.0
numpy : 1.23.1
pytz : 2022.1
dateutil : 2.8.2
setuptools : 63.4.1
pip : 22.1.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.3
IPython : 8.4.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli :
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.5.2
numba : None
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : 9.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.1
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : None

More Details About Repo
Owner Name pandas-dev
Repo Name pandas
Full Name pandas-dev/pandas
Language Python
Created Date 2010-08-24
Updated Date 2022-09-29
Star Count 35374
Watcher Count 1122
Fork Count 15034
Issue Count 3579

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
Issue with "get_stats_by_list" method in class "card" 2 2020-08-02 2022-08-31
Add link with icon to our AnitaB.org Open Source Medium 24 2021-10-08 2022-08-10
Error 404: File not found on a basic maven project 1 2022-04-18 2022-09-26
Focus on a given representation 3 2022-03-30 2022-07-28
How to hook a vocabulary class for defining new geospatial datatypes? 1 2021-01-13 2022-09-02
Ganeti 2.12 - CA is unknown 12 2021-12-14 2022-07-23
Search is not finding everything 0 2022-05-19 2022-08-10
Request 8K video support. 4 2021-07-26 2022-08-19
Typos on page /18-When-Prediction-Fails.html 0 2021-07-22 2022-09-10
Connection dropped when lowering server's user-timeout 0 2022-01-10 2022-07-23
Your C++ compiler does NOT fully support C++17 1 2021-02-04 2022-04-14
"Run a DLL as an app" Command No Longer Works 2 2022-04-07 2022-09-01
Test on ARM failed 3 2020-11-27 2022-01-15
A serious error occurred during version 3.0.3 testing“All stream threads have died. The instance will be in error state and should be closed” 9 2021-02-22 2022-07-28
Add junit5 test code for module [engineconn-plugins/jdbc] 2 2022-08-26 2022-08-28
[Solved] PlatformIO: Terminal service is not registered. 3 2021-06-26 2022-09-11
Drush command not found (zsh) 4 2021-06-09 2022-09-28
F-Droid build failed 2 2022-01-19 2022-09-14
[BUG] Setting the 'documentation' property on a custom control builderInfo has been broken at some point after 4.11.3 0 2022-07-18 2022-09-01
How to keep EditGrid in the Editing state after logic executes in "editGridSaveRow" 1 2022-07-12 2022-09-01
[UX] Provide responsive drop-down menus out of the box. 47 2016-08-30 2022-08-17
Dashboard does not show live status of Message Processors, Endpoint and Proxy services 0 2022-03-10 2022-07-26
Wrong picture in preview for shoulder quest 1 2022-06-24 2022-09-09
command-cost doesn't work in any situation where a subcommand/argument is used 1 2022-03-14 2022-09-24
Cá nhân hoán đổi vị thế của mình làm việc với các nước ngoài 0 2022-04-06 2022-09-07
Connect to BTCPayServer Node prompting for Password 11 2021-10-23 2022-08-19
Game preference = alt F4 1 2022-03-11 2022-09-08
Update Name change page to account for old crossref peer review DOIs 10 2020-12-18 2022-09-19
Add EIP Active Attached control objective 0 2021-03-11 2022-07-23
Baseline - Fix GCP Cost Polices 0 2021-03-11 2022-08-03
Endless "executing" status, export job no longer works in v3.3.1 via connect to service 16 2021-07-20 2022-09-19
M05-LAB12: Specify scope for role assignment 0 2022-04-07 2022-09-14
command-line wrongly hidden when squashing split window 0 2022-08-10 2022-08-27
quick-order-form.component.d.ts constructor is missing 1 2022-01-20 2022-09-20
how and where can i change the nodebb icon 0 2021-06-17 2022-07-24
Add implementation for UART::flush 1 2021-07-15 2022-08-14
Using `build.resolve` to use the default path resolution results in infinite loop 2 2022-04-20 2022-08-25
ig.directThread.getByParticipants returns empty items 1 2021-05-07 2022-08-14
Update Learning Guide for I2C QT Rotary Encoder re Power Connections 1 2022-02-26 2022-09-17
Perfect Scroll bar still scrolls on body when Modal Open. There should be an explicit method to unbind the scroll bar without destroying it. 2 2020-01-16 2022-03-15
Make the photos circle instead of oval on home page 4 2021-03-27 2022-07-10
If short description is available I want user to see it instead of description. 0 2021-08-06 2022-09-21
[ENHANCEMENT] tapir-0.19.x for CE2 1 2021-12-08 2022-09-14
Moving `sttp.tapir.generic` to a submodule? 2 2021-12-03 2022-09-26
Hide password when supplying basic credentials 5 2021-08-30 2022-09-05
Pie chart show only half 1 2020-03-06 2022-09-22
Can't set space as delimeter parameter in 'feedname.conf' 1 2020-04-03 2022-09-12
dap-debug for flutter is not running. 2 2020-06-26 2022-09-15
Issue with CMake setup in Visual studio 6 2021-08-25 2022-09-25
[Bug] Storybook中 `Layout` 布局中,颜色和位置不对(没有动过theme默认配置) 6 2021-11-21 2022-09-13