简体   繁体   English

使用 pandas groupby 但保持其他列的顺序,然后在组内移动

[英]Using pandas groupby but keeping the order of other columns, then shift within group

Say I have a pandas dataframe df as shown below -假设我有一个 pandas dataframe df ,如下所示 -

    a   b
0   1   23
1   2   67
2   1   98
3   1   45
4   2   64
5   3   76

I want to use groupby so the resulting dataframe is as follows -我想使用groupby所以生成的 dataframe 如下 -

    a   b
0   1   23
1   1   98
2   1   45
3   2   67
4   2   64
5   3   76

I tried df.groupby(['a', 'b']).count().reset_index() but it changes the order of rows in 'b' Next, how do I shift within a group?我试过df.groupby(['a', 'b']).count().reset_index()但它改变了'b'中的行顺序 接下来,我如何在组内移动? For example I want to groupby 'a' and shift 'b' by 1 position.例如,我想按“a”分组并将“b”移动 1 position。 So the grouped and shifted dataframe would like this -所以分组和移位的 dataframe 会像这样 -

    a   b
0   1   NA
1   1   23
2   1   98
3   2   NA
4   2   67
5   3   NA

First you want the df to be sorted on a :首先,您希望对 df a排序:

In [4501]: df = df.sort_values('a')

In [4502]: df
Out[4502]: 
   a   b
0  1  23
2  1  98
3  1  45
1  2  67
4  2  64
5  3  76

Now, you want to shift it by 1 per group:现在,您希望每组将其移动 1:

In [4504]: df['b'] = df.groupby('a')['b'].shift()

In [4505]: df
Out[4505]: 
   a     b
0  1   NaN
2  1  23.0
3  1  98.0
1  2   NaN
4  2  67.0
5  3   NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM