在将每日数据转换为每周数据时格式化索引,使用 Pandas

Formatting the index while converting daily data to weekly data, using Pandas

我已经通过查看以前的答案成功地将我的每日数据转换为每周数据,但我将日期设置为索引。我的目标是将 'Symbol' 作为索引并包含 'Date' 作为列。

我尝试在字典中包含 'Date' 并将 Symbol 作为索引,但会导致索引需要是 Datetime 的错误。

这是我的代码:

if ( data_duration == 'w' ):

    df['Date'] = pd.to_datetime(df['Date'])
    df.set_index('Date', inplace=True)
    df.sort_index(inplace=True)



def take_first(array_like):
    return array_like[0]

def take_last(array_like):
    return array_like[-1]

output = df.resample('W',                                 # Weekly resample
                    how={'Open': take_first, 
                         'High': 'max',
                         'Low': 'min',
                         'Close': take_last,
                         'Volume': 'sum'}, 
                    loffset=pd.offsets.timedelta(days=-6))  # to put the labels to Monday

df = output[['Open', 'High', 'Low', 'Close', 'Volume']]

但我想将索引保留为 'Symbol',就像它在每日数据中一样,同时将日期包含在 'Output' 中。

这是每日数据的样子:

             Date       Close      High       Low      Open    Volume
Symbol                                                            
AAPL        2017-05-25  153.87  154.3500   153.0300      153.7300      19235598
AAPL        2017-05-26  153.61  154.2400  153.3100      154.0000      21927637

然而,在每周格式化之后,除了'Symbol'之外,一切都保持不变。我该如何解决这个问题?

你想要unstack()https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html

它会将其中一个索引级别移动到 DataFrame 中的一列。像这样:

 df.unstack('Date')