What's the equivalent of cut/qcut for pandas date fields?

后端 未结 4 1772
Happy的楠姐
Happy的楠姐 2020-12-31 20:13

Update: starting with version 0.20.0, pandas cut/qcut DOES handle date fields. See What\'s New for more.

pd.cut and pd.qcut now sup

4条回答
  •  庸人自扰
    2020-12-31 21:10

    Here's a solution using pandas.PeriodIndex (caveat: PeriodIndex doesn't seem to support time rules with a multiple > 1, such as '4M'). I think the answer to your bonus question is .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
    

提交回复
热议问题