【问题标题】:Organize DataFrame into columns by year and index by day-month - PYTHON - PANDAS按年将 DataFrame 组织成列并按日月索引 - PYTHON - PANDAS
【发布时间】:2020-12-26 19:35:53
【问题描述】:

我有一个数据框,我想按日和月,年复一年地绘制。为了做到这一点,我知道我必须将年份放入自己的列中,并按日和月索引。我不知道该怎么做。

这是一个示例数据框

    date    count
2012-11-12  219
2013-11-12  188
2014-11-12  215
2015-11-12  232
2012-11-13  210
2013-11-13  234
2014-11-13  220
2015-11-13  203
2012-11-14  224
2013-11-14  196
2014-11-14  213
2015-11-14  228

应该是这样的

day-month  2012 2013 2014 2015
11-12      219   188  215  232
11-13      210   234  220  203
11-14      224   196  213  228

谢谢

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用DataFrame.pivot_table

    dates = pd.to_datetime(df['date'])
    new_df = df.pivot_table(index=[dates.dt.month, dates.dt.day], 
                            columns=dates.dt.year, 
                            values='count')
    new_df = (new_df.set_axis([f'{month}-{day}' for month, day in new_df.index])
                    .rename_axis(index='month-day', columns=None)
                  # .reset_index() # if you want column month-day 
             )
    print(new_df)
    

    输出

               2012  2013  2014  2015
    month-day                        
    11-12       219   188   215   232
    11-13       210   234   220   203
    11-14       224   196   213   228
    

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多