将每个分组中的行替换为第一行的值。 Pandas分组

3

这里有一个数据框:

df = pd.DataFrame({'A' : ['foo', 'foo', 'bar', 'bar', 'bar'],
                   'B' : ['1', '2','2', '4', '1']})

以下是我希望它看起来的样子, enter image description here 这是我的尝试失败的样子。
groups = df.groupby([A])
groups.apply(lambda g: g[g[B] == g[B].first()]).reset_index(drop=True)
2个回答

4

您可以做以下事情:

df['B'] = df.groupby('A')['B'].transform('first')

或者,如果数据已经按照如下所示的A排序:
df['B'] = df['B'].mask(df['A'].duplicated()).ffill()

输出:

     A  B
0  foo  1
1  foo  1
2  bar  2
3  bar  2
4  bar  2

我对这个的性能很好奇。 拥有171,455行和55,006个不同的组的数据集,使用%%timit。 按组进行分组的方法:77毫秒±3.83毫秒每次循环(平均值±7次运行的标准差,每次循环10次) ffill方法:16.4毫秒±1.04毫秒每次循环(平均值±7次运行的标准差,每次循环10次) 如果您的df的排序在某处发生了变化,ffill方法更容易出现错误。 - Sam

2
使用drop_duplicates+repeat
s=df.drop_duplicates('A')
s=s.reindex(s.index.repeat(df.A.value_counts()))
Out[555]: 
     A  B
0  foo  1
0  foo  1
0  foo  1
2  bar  2
2  bar  2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接