熊猫数据框获取每个组的第一行并复制到其他行

时间:2019-12-12 09:02:13

标签: python pandas dataframe

我有一个像下面的pandas DataFrame。

df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
                'value'  : ["first","second","second","first",
                            "second","first","third","fourth",
                            "fifth","second","fifth","first",
                            "first","second","third","fourth","fifth"]})

我想按[“ id”,“ value”]对此分组,获取每个组的第一行,并使用其值覆盖该组其余行中的值(因此,结果表的尺寸与源表相同)

        id   value
0        1   first
1        1  second
2        1  second
3        2  second
4        2   first
5        3   first
6        3   third
7        3  fourth
8        3   fifth
9        4  second
10       4   fifth
11       5   first
12       6   first
13       6  second
14       6   third
15       7  fourth
16       7   fifth

预期结果

        id   value
0        1   first
1        1   first
2        1   first
3        2  second
4        2  second
5        3   first
6        3   first
7        3   first
8        3   first
9        4  second
10       4  second
11       5   first
12       6   first
13       6   first
14       6   first
15       7  fourth
16       7  fourth

我尝试了许多方法,但无济于事...有什么想法吗?

1 个答案:

答案 0 :(得分:2)

GroupBy.transformGroupBy.first一起使用:

df['value'] = df.groupby('id')['value'].transform('first')