熊猫--Groupby多列返回上一个值

时间:2020-09-17 16:27:37

标签: python pandas pandas-groupby

有人问过类似的问题,但找不到我的确切案例(理想情况下没有循环)。我有

df  
    A  B  C 
    1 30 101
    1 31 220
    1 32 310
    2 30 400
    2 31 555
    2 32 616
    3 30 777
    3 31 703
    3 32 844

我想创建“ D”,其中groupby“ A”和“ B”的“ Last”返回值“ C”:

A  B  C  D
1 30 101 310
1 31 220 310
1 32 310 310
2 30 400 616
2 31 555 616
2 32 616 616
3 30 777 844
3 31 703 844
3 32 844 844

我尝试过

df['D'] = df.groupby(['A', 'B']).agg({'C': ['last']})

但是得到

TypeError: incompatible index of inserted column with frame index

然后

df['D'] = df.groupby(['A', 'B']).agg({'C': ['last']}).reset_index(0,drop=True)

并获得

ValueError: cannot reindex from a duplicate axis

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

您可以使用:

df['D'] = df.sort_values('B').groupby('A')['C'].transform('last')

输出:

   A   B    C    D
0  1  30  101  310
1  1  31  220  310
2  1  32  310  310
3  2  30  400  616
4  2  31  555  616
5  2  32  616  616
6  3  30  777  844
7  3  31  703  844
8  3  32  844  844