4

I'm trying to resample daily data to weekly data using pandas.

I'm using the following:

weekly_start_date =pd.Timestamp('01/05/2011')
weekly_end_date =pd.Timestamp('05/28/2013')

daily_data = daily_data[(daily_data["date"] >= weekly_start_date) & (daily_data["date"] <= weekly_end_date)]    

daily_data = daily_data.set_index('date',drop=False)
weekly_data = daily_data.resample('7D',how=np.sum,closed='left',label='left')

The problem is weekly_data doesn't have the date column anymore.

What did I miss?

Thanks,

4

2 回答 2

4

如果我理解您的问题,那么您似乎正确地进行了重新采样(Pandas docs on resampling here: http: //pandas.pydata.org/pandas-docs/stable/timeseries.html)。

  weekly_data = daily_data.resample('7D',how=np.sum,closed='left',label='left')

如果唯一的问题是您希望在列中复制 DateTimeIndex,您可以这样做。

  weekly_data['date'] = weekly_data.index.values

如果我误解了这个问题,我深表歉意。:)

于 2013-12-18T01:02:41.850 回答
1

您只能按数字列重新采样:

In [11]: df = pd.DataFrame([[pd.Timestamp('1/1/2012'), 1, 'a', [1]], [pd.Timestamp('1/2/2012'), 2, 'b', [2]]], columns=['date', 'no', 'letter', 'li'])

In [12]: df1 = df.set_index('date', drop=False)

In [13]: df1
Out[13]:
                          date  no letter   li
date
2012-01-01 2012-01-01 00:00:00   1      a  [1]
2012-01-02 2012-01-02 00:00:00   2      b  [2]

In [15]: df1.resample('M', how=np.sum)
Out[15]:
            no
date
2012-01-31   3

我们可以看到它使用 dtype 来确定它是否为数字:

In [16]: df1.no = df1.no.astype(object)

In [17]: df1.resample('M', how=sum)
Out[17]:
            date  no  letter  li
date
2012-01-31     0   0       0   0

实际求和的可怕技巧:

In [21]: rng = pd.date_range(weekly_start_date, weekly_end_date, freq='M')

In [22]: g = df1.groupby(rng.asof)

In [23]: g.apply(lambda t: t.apply(lambda x: x.sum(1))).unstack()
Out[23]:
                           date no letter      li
2011-12-31  2650838400000000000  3     ab  [1, 2]

日期是纪元纳秒的总和......

(希望我在做一些愚蠢的事情,并且有一种更简单的方法!)

于 2013-06-19T09:30:27.877 回答