【问题标题】:Plot DataFrame in 1 year period在 1 年期间绘制 DataFrame
【发布时间】:2018-02-16 12:28:00
【问题描述】:

我有数据框:

                    temp_old                                            temp_new
Year                2013        2014    2015    2016    2017    2018    2013    2014    2015    2016    2017    2018
Date                                                

2013-01-01 23:00:00 21.587569   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
2013-01-02 00:00:00 21.585347   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
2013-01-02 01:00:00 21.583472   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
... ... ... ... ... ... ... ... ... ... ... ... ...
2018-02-05 00:00:00 NaN         NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     22.882083
2018-02-05 01:00:00 NaN         NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     22.878472

当我绘制这个 df 时,这就是我的结果。

我的目标是展示它,但不以年为单位。所以我想在一张图表上在一月:十二月的范围内有 5 条曲线。

更新:(要绘制的代码)

df_sep_by_year.plot(figsize=(15,8))

【问题讨论】:

  • 您是否尝试从日期列中删除年份?我的意思是代替 2013-01-01 23:00:00 使用 01-01 23:00:00 并为其他记录类似地调整您的数据。
  • 同意。除非有使用 groupby 的好方法,否则简单的解决方案是创建一个没有年份的列,并将每年的年份绘制在同一个数字上。
  • 我认为这是SO Post。创建年份列,索引为 dayofyear。使用 df.plot 将列绘制为系列,x 轴为一年中的一天,从 1 到 365。

标签: python pandas dataframe matplotlib


【解决方案1】:

只需从日期列中删除年份即可。我的意思是代替 2013-01-01 23:00:00 使用 01-01 23:00:00 并对其他记录类似地调整您的数据。

# remove datetime index
df.reset_index(inplace=True)
# create new column without year, use ':02d' to correct sorting
df['new_date'] = df.Date.apply(lambda x: '{:02d}-{:02d}-{:02d}:00:00'.format(x.month, x.day, x.hour)) 
# set new index to df
df.set_index('new_date', inplace=True)
# remove old column with datetime
df = df.drop(labels=['Date'], axis=1)
# remove multiindex in columns
df.columns = [''.join(str(col)) for col in df.columns]
# join variable from different year but the same month and day
df = pd.concat([pd.DataFrame(df[x]).dropna(axis=0, how='any') for x in df_sep_by_year], axis=1).dropna(axis=1, how='all')
df.plot()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-24
    • 2020-12-31
    • 2011-02-14
    • 2021-11-20
    • 2021-07-15
    • 2020-03-26
    • 2011-04-01
    相关资源
    最近更新 更多