在Pandas中绘制日期独立于年份

时间:2013-12-20 22:18:44

标签: python matplotlib pandas

我有一个包含订单的数据框,以及每个订单发生的日期,每天允许多个订单。我已设法在数据框df中用日期绘制订单数量:

df.groupby('order_date')['order_id'].count().plot()

这持续了好几年,而我感兴趣的是每年都在绘制彼此之上,因此x轴只包含一个月和一天。我目前的尝试看起来像这样:

grouped=df.groupby([df['order_date'].map(lambda x: x.year)])
groups=[]
for name,group in grouped:
    groups.append(group)
for group in groups:
    group.groupby([group['order_date'].map(lambda x: pd.to_datetime(str(x.month)+"-"+str(x.day), format="%m-%d"))])['order_id'].count().plot() 

我按年份对所有数据进行分组,然后每年将其按照其实际日期时间在order_date中确定的月日日期时间进行分组。但是,这给了我以下错误:

 ValueError: Out of bounds nanosecond timestamp: 1-09-01 00:00:00

我认为这是我的价值观之一,但我不确定这里究竟是错的。有没有更简单的方法来做我想要的,或者我在代码中犯了错误?

1 个答案:

答案 0 :(得分:2)

我认为如果你想将每年的情节放在彼此之上,那么xax必须具有相同的日期范围。为了支持闰年,你可以将所有日期都转移到2000年,这是我的尝试:

import numpy as np
import pandas as pd

### create sample data
date = pd.date_range("2010-01-01", periods=365*3)
date = pd.Index(np.random.choice(date, 30000))
order_id = np.random.randint(10, 1000, size=30000)

df = pd.DataFrame({"date":date, "order_id":order_id})

### group by year and date
date = pd.Index(df["date"])
df2 = df["order_id"].groupby([date.year, date]).count()

### shift all year to 2000
date = df2.index.get_level_values(1)
new_date = pd.Index(pd.io.date_converters.parse_date_fields(np.ones(len(date))*2000, date.month, date.day))
year = df2.index.get_level_values(0)
df2.index = pd.MultiIndex.from_arrays([year, new_date])

### plot
p = df2.unstack(0).plot()
p.xaxis.set_ticklabels(range(1, 13));

输出:

enter image description here