替换各组中的行,用第一行的值。Pandas组比

问题描述 投票:0回答:2

这是一个数据框架。

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)
pandas dataframe pandas-groupby
2个回答
1
投票

你可以这样做。

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

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
© www.soinside.com 2019 - 2024. All rights reserved.