熊猫如何通过运行范围添加组列

问题描述

我有一个数据框:

A      B     T
0     0.1    0
0.1   0.3    0
0.35  0.48   0
1.3   1.5    0
1.5   1.9    1
2.2   2.9    1
3.1   3.4    2
5.1   5.5    3

并且我想添加一个列,该列在分组到 1.5 的 bin 后将成为 B 的排名,因此它将是

select top 1 checkdate 
from BTHI1
where CUSTOMERID = 'AUTOMO' and recordtype = 'T'
order by checkdate desc

最好的方法是什么?

解决方法

cutSeries.factorize 一起使用:

df['T'] = pd.factorize(pd.cut(df.B,bins=np.arange(0,df.B.max() + 1.5,1.5)))[0]
print (df)
      A     B  T
0  0.00  0.10  0
1  0.10  0.30  0
2  0.35  0.48  0
3  1.30  1.50  0
4  1.50  1.90  1
5  2.20  2.90  1
6  3.10  3.40  2
7  5.10  5.50  3