2013-05-01 59 views
7

更新:從版本0.20.0開始,pandas cut/qcut DOES處理日期字段。有關更多信息,請參閱What's New熊貓日期字段的cut/qcut等價物是什麼?

pd.cut和pd.qcut現在支持datetime64和timedelta64 dtypes(GH14714,GH14798)

原題:熊貓切割和qcut功能是偉大的 '瓢潑大雨' 連續數據在透視表等等中使用,但我看不到一個簡單的方法來獲取日期時間軸。因爲熊貓在所有與時間有關的東西中都非常棒!

這裏有一個簡單的例子:

def randomDates(size, start=134e7, end=137e7): 
    return np.array(np.random.randint(start, end, size), dtype='datetime64[s]') 

df = pd.DataFrame({'ship' : randomDates(10), 'recd' : randomDates(10), 
        'qty' : np.random.randint(0,10,10), 'price' : 100*np.random.random(10)}) 
df 

    price  qty recd    ship 
0 14.723510 3 2012-11-30 19:32:27 2013-03-08 23:10:12 
1 53.535143 2 2012-07-25 14:26:45 2012-10-01 11:06:39 
2 85.278743 7 2012-12-07 22:24:20 2013-02-26 10:23:20 
3 35.940935 8 2013-04-18 13:49:43 2013-03-29 21:19:26 
4 54.218896 8 2013-01-03 09:00:15 2012-08-08 12:50:41 
5 61.404931 9 2013-02-10 19:36:54 2013-02-23 13:14:42 
6 28.917693 1 2012-12-13 02:56:40 2012-09-08 21:14:45 
7 88.440408 8 2013-04-04 22:54:55 2012-07-31 18:11:35 
8 77.329931 7 2012-11-23 00:49:26 2012-12-09 19:27:40 
9 46.540859 5 2013-03-13 11:37:59 2013-03-17 20:09:09 

斌的價格或數量的羣體,我可以使用剪切/ qcut至剷鬥他們:

df.groupby([pd.cut(df['qty'], bins=[0,1,5,10]), pd.qcut(df['price'],q=3)]).count() 

         price qty recd ship 
qty  price    
(0, 1] [14.724, 46.541] 1 1 1 1 
(1, 5] [14.724, 46.541] 2 2 2 2 
     (46.541, 61.405] 1 1 1 1 
(5, 10] [14.724, 46.541] 1 1 1 1 
     (46.541, 61.405] 2 2 2 2 
     (61.405, 88.44] 3 3 3 3 

,但我看不到任何容易用我的'recd'或'ship'日期字段做同樣的事情。例如,生成一個類似的計數表,通過(比方說)recd和ship的月度桶進行細分。看起來resample()擁有所有的機制來分解時期,但我無法弄清楚如何在這裏應用它。 'date cut'中的桶(或級別)相當於一個pandas.PeriodIndex,然後我想用df ['recd']的每個值來標記它所處的時間段?

所以輸出的我要找的那種會是這樣的:

ship recv  count 
2011-01 2011-01 1 
     2011-02 3 
     ...  ... 
2011-02 2011-01 2 
     2011-02 6 
...  ...  ... 

更一般地,我想能夠混合和匹配輸出連續或分類變量。試想一下,DF還包含有紅/黃/綠值的「狀態」欄中,那麼也許我想要的狀態,價格桶,船舶和RECD桶總結計數,所以:

ship recv  price status count 
2011-01 2011-01 [0-10) green  1 
          red  4 
       [10-20) yellow  2 
        ...  ... ... 
     2011-02 [0-10) yellow  3 
     ...  ...  ... ... 

作爲獎勵的問題,什麼是修改上面的groupby()結果只包含一個名爲'count'的單個輸出列的最簡單方法是什麼?

回答

4

下面是使用pandas.PeriodIndex(警告:PeriodIndex不支持 似乎支持多> 1的時間規則,如'4M')的解決方案。我認爲 你的獎金問題的答案是.size()

In [49]: df.groupby([pd.PeriodIndex(df.recd, freq='Q'), 
    ....:    pd.PeriodIndex(df.ship, freq='Q'), 
    ....:    pd.cut(df['qty'], bins=[0,5,10]), 
    ....:    pd.qcut(df['price'],q=2), 
    ....:   ]).size() 
Out[49]: 
       qty  price 
2012Q2 2013Q1 (0, 5] [2, 5] 1 
2012Q3 2013Q1 (5, 10] [2, 5] 1 
2012Q4 2012Q3 (5, 10] [2, 5] 1 
     2013Q1 (0, 5] [2, 5] 1 
       (5, 10] [2, 5] 1 
2013Q1 2012Q3 (0, 5] (5, 8] 1 
     2013Q1 (5, 10] (5, 8] 2 
2013Q2 2012Q4 (0, 5] (5, 8] 1 
     2013Q2 (0, 5] [2, 5] 1 
4

只需要設置你想通過重新取樣領域的指數,這裏的一些例子

In [36]: df.set_index('recd').resample('1M',how='sum') 
Out[36]: 
       price qty 
recd      
2012-07-31 64.151194 9 
2012-08-31 93.476665 7 
2012-09-30 94.193027 7 
2012-10-31   NaN NaN 
2012-11-30   NaN NaN 
2012-12-31 12.353405 6 
2013-01-31   NaN NaN 
2013-02-28 129.586697 7 
2013-03-31   NaN NaN 
2013-04-30   NaN NaN 
2013-05-31 211.979583 13 

In [37]: df.set_index('recd').resample('1M',how='count') 
Out[37]: 
2012-07-31 price 1 
      qty  1 
      ship  1 
2012-08-31 price 1 
      qty  1 
      ship  1 
2012-09-30 price 2 
      qty  2 
      ship  2 
2012-10-31 price 0 
      qty  0 
      ship  0 
2012-11-30 price 0 
      qty  0 
      ship  0 
2012-12-31 price 1 
      qty  1 
      ship  1 
2013-01-31 price 0 
      qty  0 
      ship  0 
2013-02-28 price 2 
      qty  2 
      ship  2 
2013-03-31 price 0 
      qty  0 
      ship  0 
2013-04-30 price 0 
      qty  0 
      ship  0 
2013-05-31 price 3 
      qty  3 
      ship  3 
dtype: int64 
+1

這似乎不是一個通用的解決方案,例如,如果我想在兩個不同的日期,或日期和非日期(通過剪切或類別變量)分組。我將用我正在尋找的輸出結構更新這個問題。 – patricksurry 2013-05-01 14:22:40

0

如何使用Series,並把您感興趣到了DataFrame的部分,然後在系列對象上調用cut

price_series = pd.Series(df.price.tolist(), index=df.recd) 

然後

pd.qcut(price_series, q=3) 

等。 (雖然我認爲@傑夫的答案是最好的)

1

我想出了一個想法,它依賴於datetime64 [ns]的底層存儲格式。如果你定義的dcut()這樣的

def dcut(dts, freq='d', right=True): 
    hi = pd.Period(dts.max(), freq=freq) + 1 # get first period past end of data 
    periods = pd.PeriodIndex(start=dts.min(), end=hi, freq=freq) 
    # get a list of integer bin boundaries representing ns-since-epoch 
    # note the extra period gives us the extra right-hand bin boundary we need 
    bounds = np.array(periods.to_timestamp(how='start'), dtype='int') 
    # bin our time field as integers 
    cut = pd.cut(np.array(dts, dtype='int'), bins=bounds, right=right) 
    # relabel the bins using the periods, omitting the extra one at the end 
    cut.levels = periods[:-1].format() 
    return cut 

然後我們可以做什麼,我想:

df.groupby([dcut(df.recd, freq='m', right=False),dcut(df.ship, freq='m', right=False)]).count() 

要獲取:

   price qty recd ship 
2012-07 2012-10 1 1 1 1 
2012-11 2012-12 1 1 1 1 
     2013-03 1 1 1 1 
2012-12 2012-09 1 1 1 1 
     2013-02 1 1 1 1 
2013-01 2012-08 1 1 1 1 
2013-02 2013-02 1 1 1 1 
2013-03 2013-03 1 1 1 1 
2013-04 2012-07 1 1 1 1 
     2013-03 1 1 1 1 

我想你可以同樣定義dqcut(),它首先將每個日期時間值「四捨五入」爲表示其包含期間開始的整數(以您指定的頻率),然後使用qcut()在這些邊界之間進行選擇。或者先對原始整數值執行qcut(),然後根據您選擇的頻率對生成的bin進行四捨五入?

獎勵問題沒有喜悅嗎? :)