11

私は次のデータフレームを持っています:

df = pd.DataFrame({
'Branch' : 'A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Joe Joe Carl'.split(),
'Quantity': [1,3,5,8,9,3],
'Date' : [
DT.datetime(2013,1,1,13,0),
DT.datetime(2013,1,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,12,2,12,0),                                      
DT.datetime(2013,12,2,14,0),
]})

from pandas.tseries.resample import TimeGrouper

TimeGrouper を使用して、このデータを支店ごとに 20 日間でグループ化するにはどうすればよいですか?

TimeGrouper を groupby 関数の別の引数と組み合わせることができなかったため、以前の試みはすべて失敗しました。

よろしくお願いいたします。

ありがとうございました

アンディ

4

2 に答える 2

17

TimeGrouper を別の列で使用できるようになりました ( IIRC pandasバージョン0.14以降):

In [11]: df1 = df.set_index('Date')

In [12]: g = df1.groupby([pd.TimeGrouper('20D'), 'Branch'])

In [13]: g.sum()
Out[13]:
                            Quantity
Date                Branch
2013-01-01 13:00:00 A              4
2013-09-18 13:00:00 A             13
2013-11-17 13:00:00 A              9
                    B              3
于 2015-02-04T00:21:06.430 に答える
5

ここでの議論から: https://github.com/pydata/pandas/issues/3791

In [38]: df.set_index('Date').groupby(pd.TimeGrouper('6M')).apply(lambda x: x.groupby('Branch').sum())
Out[38]: 
                   Quantity
           Branch          
2013-01-31 A              4
2014-01-31 A             22
           B              3

そして、もう少し複雑な質問

In [55]: def testf(df):
   ....:     if (df['Buyer'] == 'Mark').sum() > 0:
   ....:         return Series(dict(quantity = df['Quantity'].sum(), buyer = 'mark'))
   ....:     return Series(dict(quantity = df['Quantity'].sum()*100, buyer = 'other'))
   ....: 

In [56]: df.set_index('Date').groupby(pd.TimeGrouper('6M')).apply(lambda x: x.groupby('Branch').apply(testf))
Out[56]: 
                   buyer quantity
           Branch                
2013-01-31 A        mark        4
2014-01-31 A       other     2200
           B       other      300
于 2013-06-07T15:41:04.273 に答える