首页 > 解决方案 > Pandas pivot_table 发出关于在日期类型的数据集上使用边距时推断 datetime64 的 FutureWarning

问题描述

创建在索引中包含日期字段的数据透视表时出现FutureWarning错误:

<ipython-input-22-330e19e65ef9>: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_report = pd.pivot_table(

这是触发它的代码:

pivot_report = pd.pivot_table(
    data.loc[(data["year"] == year_to_report)], 
    index = ["Category", "Subcategory", "date"], 
    values = [ "amount"], 
    aggfunc = [np.sum], 
    margins = True)
pivot_report

数据是从具有显式类型的 csv 读取的,并且该字段似乎在调用之前date已正确转换为,所以我不清楚它为什么抱怨类型推断。datetime64pivot_table

data['date']
0       2021-09-10
1       2021-09-08
2       2021-09-08
3       2021-09-08
4       2021-09-08
           ...    
37299   2008-07-31
37300   2008-07-31
37301   2008-07-31
37302   2008-07-31
37303   2008-07-31
Name: date, Length: 37304, dtype: datetime64[ns]

但是我注意到,虽然该margins参数All按预期在底部添加了一行,显示了该amount字段的总计,但它也显示了NaT该字段的总计date

                                                       sum
                                                    amount
Category         Subcategory        date                  
Auto & Transport Advertising        2021-01-01        0.00
                                    2021-01-02        0.00
                                    2021-01-03        0.00
                                    2021-01-04        0.00
                                    2021-01-05        0.00
...                                                    ...
Vacation         Withdrawal         2021-09-06        0.00
                                    2021-09-07        0.00
                                    2021-09-08        0.00
                                    2021-09-10        0.00
All                                 NaT             134.31

[928450 rows x 1 columns]

这是预期的吗?为什么margins要尝试为日期字段提供总计?这会解释类型推断FutureWarning消息吗?

标签: pythonpython-3.xpandaspivot-table

解决方案


推荐阅读