Pandas按区间分组

3

我有一个数据框,其中包含名为month的列,该列包含1-12月份的数字。

示例:

  Index     month  
  0          1        
  1          9         
  2          12       

我想将这一列分成四个区间: 1-3 4-6 7-9 10-12 因此,每行都会被放入其中一个区间。 我该怎么做?
3个回答

4
你可以使用商运算符按季度进行拆分:
df['quarter'] = df['month'] // 4 + 1

或者您可以使用numpy.digitize来明确定义区间:

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

1
哇,这几乎太简单了 df['quarter'] = df['month'] // 4 + 1 - Mathias Lund

2
您可以使用 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)]

或者
pd.to_datetime(df.month,format='%m').dt.quarter
Out[308]: 
0    1
1    3
2    4
Name: month, dtype: int64

1
你可以编写一个快速函数来完成这个任务,然后将其应用于DataFrame,生成季度月份范围的字符串。
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接