我有一个数据框,其中包含名为month
的列,该列包含1-12月份的数字。
示例:
Index month
0 1
1 9
2 12
我想将这一列分成四个区间:
1-3
4-6
7-9
10-12
因此,每行都会被放入其中一个区间。
我该怎么做?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
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
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
! - Mathias Lund