我的数据框
下面的数据框由“年”、“月”和“数据”作为列:
np.random.seed(0)
df = pd.DataFrame(dict(
Year = [2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003],
Month = [1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12],
Data = np.random.randint(21,100,size=36)))
df
我想要一种Pythonic方式将其转换为时间序列数据,这样我就可以将“Data”和“Data”作为时间序列数据而不是数据帧。
我尝试过的
我已经尝试过:
import pandas as pd
timeseries = data.assign(Date=pd.to_datetime(data[['Year', 'Month']].assign(day=1)))
columns = ['Year','Month']
df.drop(columns, inplace=True, axis=1) # 我不需要日期,而是年份和月份 时间序列
但新数据仅在数据框中添加名为“日期”的列。
我想要什么
我想要一个由“日期”(例如2001-1)和“数据”列组成的时间序列数据,这样我就可以制作时间图,用数据进行时间序列分析和预测。
我的意思是如何索引此类时间序列数据,以便当我使用此代码进行绘图时:
plt.figure(figsize=(5.5, 5.5))
data1['Data'].plot(color='b')
plt.title('Monthly Data')
plt.xlabel('Data')
plt.ylabel('Data')
plt.xticks(rotation=30)
我将把我的 x 轴作为数据而不是数字进行分级
最佳答案
IIUC,你的方法很好,让 pandas 绘图处理 x 轴。
ax = df.set_index(pd.to_datetime(df[['Year','Month']].assign(day=1)))['Data']\
.plot(color='b', figsize=(5.5,5.5), title='Monthly Data')
_ = ax.set_xlabel('Data')
_ = ax.set_ylabel('Data')
输出:
关于python - 如何组合数据框的月份和年份列以形成时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975561/