简体   繁体   English

按年将 DataFrame 组织成列并按日月索引 - PYTHON - PANDAS

[英]Organize DataFrame into columns by year and index by day-month - PYTHON - PANDAS

I have a dataframe that I would like to plot by day and month, year on top of year.我有一个 dataframe ,我想按日和月,年在年之上 plot 。 In order to do that I understand that I have to put the years into their own columns and index by day and month.为了做到这一点,我知道我必须将年份放入自己的列中,并按日和月进行索引。 I am not sure how to go at it.我不确定如何使用 go。

Here is a sample data frame这是一个示例数据框

    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

which should look something like this它应该看起来像这样

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

Thanks谢谢

Use DataFrame.pivot_table使用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)

Output Output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python Pandas 数据框:对于一年中的每个月,如果月份不存在,则将当月最后一天的日期添加到索引中,或者删除重复项 - Python Pandas dataframe: For each month of the year, add the date with last day in the month to an index if month not present, or remove duplicates 熊猫:当索引为年月且列为日时,将DataFrame转换为Series - Pandas: Convert a DataFrame into a Series when index is Year-Month and columns are Day Python:按小时,日和月(按年份分组)过滤熊猫中的DataFrame - Python: Filter DataFrame in Pandas by hour, day and month grouped by year Django 过滤器与“日-月”一起过滤而不考虑年份 - Django filter with 'day-month' together without consider year Pandas,Python:旋转数据帧的一些(31天)列,并将它们与现有(年,月)行匹配(NOAA数据) - Pandas, Python: rotate some (31-day) columns of a dataframe and match them to the existing (year, month) rows (NOAA data) 在python / pandas中将年/月转换为年/月/日 - Convert year/month to year/month/day in python/pandas Python Pandas groupby月日年周 - Python Pandas groupby month day year week 使用python / pandas将月,日,年转换为月,年? - Convert month,day,year to month,year with python/pandas? 熊猫DataFrame索引-仅月和日 - Pandas DataFrame index - month and day only 将年转换为年-月-日python csv - converting year to year-month-day python pandas csv
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM