Pandas 如何基于一列将其他列中的连续值分组到范围中

Pandas 如何基于一列将其他列中的连续值分组到范围中,pandas,numpy,Pandas,Numpy,我有以下数据帧: 我想从dataframe获得以下输出 是否仍然可以使用groupby聚合函数、pandas中的pivot_表基于列“A”对其他列[“B”、“索引”]进行分组 我想不出一种编写代码的方法 使用: df=df.reset_index() #if 'index' not is a colum g=df['A'].ne(df['A'].shift()).cumsum() new_df=df.groupby(g,as_index=False).agg(index=('index',lis

我有以下数据帧:

我想从dataframe获得以下输出

是否仍然可以使用groupby聚合函数、pandas中的pivot_表基于列“A”对其他列[“B”、“索引”]进行分组

我想不出一种编写代码的方法

使用:

df=df.reset_index() #if 'index' not is a colum
g=df['A'].ne(df['A'].shift()).cumsum()
new_df=df.groupby(g,as_index=False).agg(index=('index',list),A=('A','first'),B=('B',lambda x: list(x.unique())))
print(new_df)

在大熊猫中。这正是人们所期望的。
new_df=df.groupby(g,as_index=False).agg({'index':list,'A':'first','B':lambda x: list(x.unique())})
new_df=df.groupby(g,as_index=False).agg(index=('index',lambda x: list(x.unique())),A=('A','first'),B=('B',lambda x: list(x.unique())))
print(new_df)
df=pd.DataFrame({'index':range(20),
                 'A':[1,1,1,1,2,2,0,0,0,1,1,1,1,1,1,0,0,0,3,3]
                 ,'B':[1,2,3,5,5,5,7,8,9,9,9,12,12,14,15,16,17,18,19,20]})
print(df)
    index  A   B
0       0  1   1
1       1  1   2
2       2  1   3
3       3  1   5
4       4  2   5
5       5  2   5
6       6  0   7
7       7  0   8
8       8  0   9
9       9  1   9
10     10  1   9
11     11  1  12
12     12  1  12
13     13  1  14
14     14  1  15
15     15  0  16
16     16  0  17
17     17  0  18
18     18  3  19
19     19  3  20
g=df['A'].ne(df['A'].shift()).cumsum()
new_df=df.groupby(g,as_index=False).agg(index=('index',list),A=('A','first'),B=('B',lambda x: list(x.unique())))
print(new_df)

                     index  A                B
0             [0, 1, 2, 3]  1     [1, 2, 3, 5]
1                   [4, 5]  2              [5]
2                [6, 7, 8]  0        [7, 8, 9]
3  [9, 10, 11, 12, 13, 14]  1  [9, 12, 14, 15]
4             [15, 16, 17]  0     [16, 17, 18]
5                 [18, 19]  3         [19, 20]