Python Pandas:将 DataFrame 组的最后一个值分配给该组的所有条目

Python Pandas: Assign Last Value of DataFrame Group to All Entries of That Group

在PythonPandas中,我有一个DataFrame。我按列对这个 DataFrame 进行分组,并希望将一列的最后一个值分配给另一列的所有行。

我知道我可以通过这个命令 select 组的最后一行:

import pandas as pd

df = pd.DataFrame({'a': (1,1,2,3,3), 'b':(20,21,30,40,41)})
print(df)
print("-")
result = df.groupby('a').nth(-1)
print(result)

结果:

   a   b
0  1  20
1  1  21
2  2  30
3  3  40
4  3  41
-
    b
a    
1  21
2  30
3  41

如何将此操作的结果分配回原始数据帧,以便我得到类似的东西:

   a   b b_new
0  1  20 21
1  1  21 21
2  2  30 30
3  3  40 41
4  3  41 41

使用transform with last:

df['b_new'] = df.groupby('a')['b'].transform('last')

选择:

df['b_new'] = df.groupby('a')['b'].transform(lambda x: x.iat[-1])

print(df)
   a   b  b_new
0  1  20     21
1  1  21     21
2  2  30     30
3  3  40     41
4  3  41     41

nth and join 的解决方案:

df = df.join(df.groupby('a')['b'].nth(-1).rename('b_new'), 'a')
print(df)
   a   b  b_new
0  1  20     21
1  1  21     21
2  2  30     30
3  3  40     41
4  3  41     41

时间:

N = 10000

df = pd.DataFrame({'a':np.random.randint(1000,size=N),
                   'b':np.random.randint(10000,size=N)})

#print (df)


def f(df):
    return df.join(df.groupby('a')['b'].nth(-1).rename('b_new'), 'a')

#cᴏʟᴅsᴘᴇᴇᴅ1
In [211]: %timeit df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))
100 loops, best of 3: 3.57 ms per loop

#cᴏʟᴅsᴘᴇᴇᴅ2
In [212]: %timeit df['b_new'] = df.a.replace(df.groupby('a').b.nth(-1))
10 loops, best of 3: 71.3 ms per loop

#jezrael1
In [213]: %timeit df['b_new'] = df.groupby('a')['b'].transform('last')
1000 loops, best of 3: 1.82 ms per loop

#jezrael2
In [214]: %timeit df['b_new'] = df.groupby('a')['b'].transform(lambda x: x.iat[-1])
10 loops, best of 3: 178 ms per loop
    
#jezrael3
In [219]: %timeit f(df)
100 loops, best of 3: 3.63 ms per loop

警告

结果没有解决给定组数的性能问题,这将对其中一些解决方案的计时产生很大影响。

两种可能性,groupby + nth + mapreplace

df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))

或者,

df['b_new'] = df.a.replace(df.groupby('a').b.nth(-1))

您也可以将 nth(-1) 替换为 last()(事实上,这样做恰好可以加快速度),但是 nth 让您更灵活地选择项目来自 b.

中的每个组
df

   a   b  b_new
0  1  20     21
1  1  21     21
2  2  30     30
3  3  40     41
4  3  41     41

我认为这应该很快

df.merge(df.drop_duplicates('a',keep='last'),on='a',how='left')
Out[797]: 
   a  b_x  b_y
0  1   20   21
1  1   21   21
2  2   30   30
3  3   40   41
4  3   41   41