Python 按间隔分组

Python 按间隔分组,python,pandas,Python,Pandas,我有一个数据框,其中有一列名为month,其中包含从1到12的月份数 例如: Index month 0 1 1 9 2 12 我想将此列拆分为四分之一间隔: 1-3 4-6 7-9 10-12 所以每一行都被放入其中一个间隔。 我该怎么做?您可以使用pd.cut pd.cut(df.month,[0,4,7,10,13],right=False) Out[298]

我有一个数据框,其中有一列名为
month
,其中包含从1到12的月份数

例如:

  Index     month  
  0          1        
  1          9         
  2          12       
我想将此列拆分为四分之一间隔:
1-3
4-6
7-9
10-12

所以每一行都被放入其中一个间隔。
我该怎么做?

您可以使用
pd.cut

pd.cut(df.month,[0,4,7,10,13],right=False)
Out[298]: 
0      [0, 4)
1     [7, 10)
2    [10, 13)
Name: month, dtype: category
Categories (4, interval[int64]): [[0, 4) < [4, 7) < [7, 10) < [10, 13)]

可以使用商运算符按四分之一拆分:

df['quarter'] = df['month'] // 4 + 1
或者,您可以使用显式定义存储箱:

df['quarter'] = np.digitize(df['month'], [3, 6, 9], right=True) + 1

print(df)

   Index  month  quarter
0      0      1        1
1      1      9        3
2      2     12        4

您可以编写一个快速函数来执行此操作,然后将其应用于数据帧,该数据帧将以字符串形式生成季度-月份范围

def quarter_range(x):
    q = int(np.floor(x / 4.) + 1)
    qr = "-".join([str(q), str(q+2)])
    return qr

df["quarter_label"] = df["month"].apply(quarter_range)

哇,那简直太简单了
df['quarter']=df['month']//4+1
def quarter_range(x):
    q = int(np.floor(x / 4.) + 1)
    qr = "-".join([str(q), str(q+2)])
    return qr

df["quarter_label"] = df["month"].apply(quarter_range)