在间隔列表上自定义 pandas groupby

Custom pandas groupby on a list of intervals

我有一个数据框df:

     A    B
0   28  abc
1   29  def
2   30  hij
3   31  hij
4   32  abc
5   28  abc
6   28  abc
7   29  def
8   30  hij
9   28  abc
10  29  klm
11  30  nop
12  28  abc
13  29  xyz

df.dtypes

A    object        # A is a string column as well
B    object
dtype: object

我想将此列表中的值用于 groupby:

i = np.array([ 3,  5,  6,  9, 12, 14])

基本上,df 中索引为 0、1、2 的所有行都在第一组中,索引为 3、4 的行在第二组中,索引为 5 的行在第三组中,等等。

我的最终目标是:

A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz

目前使用 groupby + pd.cut 的解决方案:

df.groupby(pd.cut(df.index, bins=np.append([0], i)), as_index=False).agg(','.join)

          A            B
0  29,30,31  def,hij,hij
1     32,28      abc,abc
2        28          abc
3  29,30,28  def,hij,abc
4  29,30,28  klm,nop,abc
5        29          xyz

结果不正确:-(

我怎样才能正确地做到这一点?

你非常接近,但是在 pd.cut 中使用 include_lowest=Trueright=False 因为你想要容器中的第 0 个索引然后你不想包括每个垃圾箱的最后一个元素,即

idx = pd.cut(df.index, bins=np.append([0], i), 
                      include_lowest=True, right=False)
df.groupby(idx, as_index=False).agg(','.join)
A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz

我认为这可能会很快..

df['G']=0
np.put(df.G,i-1,[1]*len(i))
df.groupby(df.G.iloc[::-1].cumsum())[['A','B']].agg(lambda x: ','.join(x.astype(str))).sort_index(ascending =False)
Out[772]: 
          A            B
G                       
6  28,29,30  abc,def,hij
5     31,32      hij,abc
4        28          abc
3  28,29,30  abc,def,hij
2  28,29,30  abc,klm,nop
1     28,29      abc,xyz