我已经通过查看以前的答案设法将每日数据转换为每周数据,但我将日期设置为索引。我的目标是将“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']]
但我想将索引保留为“符号”,就像它在每日数据中一样,同时在“输出”中包含日期。
这是每日数据的样子:
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')
