我有一个数据框,其中一些行除一列外具有所有相同的值。我希望删除重复的行,仅保留该列中值为 1 的每个组中的第一行,或者如果该列中没有值为 1 的值则保留任意行。示例数据:
df = pd.DataFrame({'a': [1, 1, 1, 2, 2, 3, 3],
'b': [0, 1, 2, 3, 4, 5, 6],
'c': [0, 1, 0, 0, 0, 1, 1]})
我想要的输出是这样的
df.groupby(['a']).first_where(lambda row: row['c'] == 1).reset_index()
a b c
0 1 1 1
1 2 4 0
2 3 5 1
最佳答案
您可以使用drop_duplicates
df.sort_values(['a','c']).drop_duplicates(['a'],keep='last')
Out[748]:
a b c
1 1 1 1
4 2 4 0
6 3 6 1
如果你想使用groupby
df.sort_values(['a','c']).groupby('a',as_index=False).last()
Out[750]:
a b c
0 1 1 1
1 2 4 0
2 3 6 1
关于python - Pandas groupby 获取行匹配条件的组的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48773602/