【问题标题】:How to Combine Month and Year columns of Data frame to form Time Series Data如何组合数据框的月和年列以形成时间序列数据
【发布时间】:2019-03-29 06:09:29
【问题描述】:

我的数据框

以下数据框由“年”、“月”和“数据”作为列组成:

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

我想要一种 Python 方式将其转换为时间序列数据,这样我就可以将“数据”和“数据”作为时间序列数据而不是数据框。

我尝试了什么

我试过了:

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 轴将作为数据而不是数字毕业

【问题讨论】:

    标签: python pandas datetime dataframe


    【解决方案1】:

    IIUC,你的方法很好,让 pandas plot 处理 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')
    

    输出:

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2015-02-19
      • 2020-10-19
      • 1970-01-01
      相关资源
      最近更新 更多