【问题标题】:pandas resample to get monthly average with time series datapandas 重新采样以获得具有时间序列数据的月平均值
【发布时间】:2019-09-17 08:00:38
【问题描述】:

我正在使用来自 tableau (https://community.tableau.com/thread/194200) 的时间序列数据集,其中包含每日家具销售额,我想重新采样以获得平均每月销售额。

我尝试在 Pandas 中使用 resample 来获得月平均值:

There are four days in January selling furniture, 
and there is no sales in the rest of Jan.

Order Date   Sales
...
2014/1/6     2573.82
2014/1/7     76.728
2014/1/16    127.104
2014/1/20    38.6
...

y_furniture = furniture['Sales'].resample('MS').mean()

我希望结果是每月的实际平均销售额。

也就是说,所有的日销售额加起来除以 31 天,即 90.85,但代码将总和除以 4,约为 704。这并不能正确反映实际的月销售额。

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: python-3.x pandas time-series


    【解决方案1】:

    您可以使用数据透视表获取每月的平均销售额: 试试:

    df['Order_date']=pd.to_datetime(df['Order_date'])
    df['Month']=df['Order_date'].dt.month
    df_pivot=df.pivot_table(columns='Month',aggfunc='mean')
    

    【讨论】:

      【解决方案2】:

      我不确定您的预期答案是 90.85 还是 704。所以我是 为两者提供解决方案,根据您的要求选择它。

      l1 = ['Order Date',
            'Sales',
            ]
      l2 = [['2014/1/6',2573.82],
              ['2014/1/7',76.728],
              ['2014/1/16',127.104],
              ['2014/1/20',38.6],
              ['2014/2/20',38.6],
           ]
      df = pd.DataFrame(l2, columns=l1)
      
      df['Order Date'] = pd.to_datetime(df['Order Date'])  #make sure Order Date is of Date type
      
      
      
      x = df.groupby(df['Order Date'].dt.month).mean()  #or .agg('mean')
      #### Output  ####
      Order Date         
      1           704.063
      2            38.600
      
      
      
      def doCalculation(df):
          groupSum = df['Sales'].sum()
          return (groupSum / df['Order Date'].dt.daysinmonth)
      
      y = df.groupby(df['Order Date'].dt.month).apply(doCalculation).groupby(['Order Date']).mean()
      
      #### Output ####
      Order Date
      1    90.846839
      2     1.378571
      

      【讨论】:

        猜你喜欢
        • 2019-07-12
        • 1970-01-01
        • 2021-08-01
        • 2019-03-15
        • 2021-04-07
        • 2022-11-27
        • 2019-03-02
        • 2019-01-18
        • 1970-01-01
        相关资源
        最近更新 更多