python - 如何组合数据框的月份和年份列以形成时间序列数据

标签 python pandas datetime dataframe

我的数据框

下面的数据框由“年”、“月”和“数据”作为列:

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')

输出:

enter image description here

关于python - 如何组合数据框的月份和年份列以形成时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975561/

相关文章:

python - 如何通过数据框的值重新索引数据框?

oracle - 从Grails-Groovy中提取Oracle vs MySQL中的时间戳字段

python - Postgres+SQLAlchemy 在使用 default=func.now() 时将时间转换为 UTC

python - 随机梯度下降和性能

python - 为什么 travis CI 中的服务器机器无法找到我的需求文件?

python - ObjectPath: "in"运算符有问题

python - 数据框合并+与存在性测试比较

python - 整数除法四舍五入

Python:对交易进行分类的最有效方法

java - 根据当前时区与东部时区的时差更改 LocalDateTime