2016-02-24 41 views
2

我試圖繪製已被某些日期範圍分類的數據。在熊貓中按日期進行分組以便繪製分類分佈

例如說我有以下數據框:

dates = pd.date_range(start=pd.datetime(2013, 6, 1), periods=50, freq='D') 
df = pd.DataFrame(np.random.normal(10, 3, 50), columns=['x'], index=dates) 
df[:3] 
      x 
2013-06-01 9.819422 
2013-06-02 3.659629 
2013-06-03 14.862231 

我想組3周的間隔日期,並繪製數據,這給了我,我要找的平均水平,

df.resample('3w', how='mean') 

      x 
2013-06-02 11.424715 
2013-06-23 9.443888 
2013-07-14 8.572851 
2013-08-04 9.873879 

但我想保留所有的數據,以便我可以在seaborn中使用箱圖或包含使用matplotlib的標準錯誤。我完全停留在如何在沒有明確定義範圍的情況下實現這一點(這與我正在使用的實際數據框無法實現)。這似乎是必須有可以做到這一點的大熊貓所以輸出會是這樣的一個相當簡單的方法:

  x   week 
2013-06-01 9.819422 1 
2013-06-02 3.659629 1 
2013-06-03 14.862231 1 

哪裏week爲代表的分級數據的分類變量。任何想法將不勝感激。

回答

2

也許你可以使用TimeGrouper。

df.groupby(pd.TimeGrouper('3w', how=np.mean)).describe().unstack() 
       x                   
      count  mean  std  min  25%  50%  75%  max 
2013-06-02  2 10.864835 3.794379 8.181803 9.523319 10.864835 12.206350 13.547866 
2013-06-23 21 9.888556 3.452331 3.503944 7.838625 9.739525 12.403285 16.031644 
2013-07-14 21 10.475142 2.687320 6.605619 8.399518 11.209683 11.818895 16.265771 
2013-08-04  6 9.471931 3.196345 5.492205 8.122607 8.502217 10.901065 14.638198 

>>> g = df.groupby(pd.TimeGrouper('3w', how=np.mean)).boxplot() 

enter image description here

的時期的開始日期(字符串)添加到原數據:

df = pd.DataFrame(np.random.normal(10, 3, 50), columns=['x'], index=dates) 
tg = df.groupby(pd.TimeGrouper('3W', closed='left')) 
df['period'] = None 
for p, idx in tg.indices.iteritems(): 
    df.ix[idx, 'period'] = p.strftime('%Y-%m-%d') 

>>> df.head() 
        x  period 
2013-06-01 7.972202 2013-06-16 
2013-06-02 12.184312 2013-06-16 
2013-06-03 6.884374 2013-06-16 
2013-06-04 8.414091 2013-06-16 
2013-06-05 12.368407 2013-06-16 
+0

這非常適用於大多數情況下,但是,我真的希望能夠產生如我所提供的數據框一個例子,因爲我還希望能夠計算其他統計數據。 – johnchase

+0

嘗試'tg = df.groupby(pd.TimeGrouper('3w'))'並使用'tg.'完成製表符以查看可用的方法。請注意'.get_group'以及所有其他可用的統計信息。 – Alexander

1

在這裏,我會怎麼做:

for idx,w in enumerate(df.groupby(pd.TimeGrouper("3w-SAT"))): # your first day is a saturday 
    df.loc[w[0], "week"] = idx+1 

# propagate the week number 
df["week"] = df.week.fillna(method="ffill") 

# remove added date by the Timegrouper as your number of date is not a multiple of 3 weeks. 
df.dropna(inplace=1) 
df.tail() 

        x week 
2013-07-16 15.717111  3 
2013-07-17 9.815201  3 
2013-07-18 9.426426  3 
2013-07-19 12.725350  3 
2013-07-20 16.100748  3 


# just use seaborn as usual 
sns.boxplot(data=df, x="week", y="x") # plot it 

Timegrouper seaborn

我不知道是否有使用TimeGrouper與seaborn一種更好的方式直接

HTH

+0

謝謝,這是一個很好的建議。我在整個數據集上運行時遇到錯誤,我想因爲有重複的時間索引,但我不積極,我需要進一步調查。 – johnchase

+0

@johnchase,儘量減少你的數據集,並分享它,所以我們可以重現錯誤。 (或製造另一個重現錯誤的假冒) – jrjc