我的数据帧
以下数据框架由“年份”、“月份”和“数据”作为栏组成:
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我想用一种仿生的方式将它转换成时间序列数据,这样我就可以将“数据”和“数据”作为时间序列数据而不是数据帧。
我试过什么
我试过:
import pandas as pd
timeseries = data.assign(Date=pd.to_datetime(data[['Year', 'Month']].assign(day=1)))
columns = ['Year','Month']Df.drop(列,inplace=True,axis=1) #我不需要日期,而需要年月时间序列
但是,新的数据只向数据框架添加了一个名为"Date“的列。
我想要什么
我想要一个时间序列数据,它将包括“日期”(例如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轴刻度为数据而不是数字。
发布于 2018-10-24 19:08:55
IIUC,你的方法很好,让熊猫画出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')输出:

https://stackoverflow.com/questions/52975561
复制相似问题