在熊猫时间序列中将月度数据转换为年度数据

时间:2020-10-09 21:32:17

标签: python pandas dataframe time-series

我有一个数据框,每个月末都有股票的收盘价。如何汇总数据,以便获得每年的收盘价。

样本数据:

enter image description here

我有以下代码

import pandas as pd
data = pd.read_csv("historical_data.csv")
df = pd.DataFrame(data)
print(df.head())
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df.index = pd.to_datetime(df.index)
df.resample('A')
print(df.head())

我在某处读到“ A”是用于“年度”汇总的参数, 但我只是得到了相同的输出,而没有年度汇总。

1 个答案:

答案 0 :(得分:1)

您需要重新分配重新采样的结果。另外,使用.last()获取每年的最新价格。

df = df.resample('A').last()