我想分配组的第一行。
输入:
df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B'],
'col2': [1, 1, 2, 3],
'col3': ['value1', 'value2', 'value3', 'value4']})
我尝试过:
df.groupby(['col1', 'col2']).first()
但我只拿回第一行。
我想要这个输出:
col1 col2 col3 first_row A 1 value1 True A 1 value2 False B 2 value3 True B 3 Value4 True
最佳答案
使用groupby.cumcount
和 eq
。如果累计计数等于0,则为第一行:
df['first_row'] = df.groupby(['col1', 'col2']).cumcount().eq(0)
[输出]
col1 col2 col3 first_row
0 A 1 value1 True
1 A 1 value2 False
2 B 2 value3 True
3 B 3 value4 True
关于python - 在 Pandas 中分配组的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63230961/