[英]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.