avi*_*iss 4 python group-by dataframe pandas pandas-groupby
我有一个数据框,我需要对其进行分组id,然后对time每个数据框进行排序,并仅保留第一条记录id。尝试了其他答案中建议的不同方法,但无法获得正确的结果。将感谢您的帮助!
test = pd.DataFrame({'id' : [1,1,1,
2,2,
3,3,3,3],
'ref' : ["search","social","direct",
"social","direct",
"direct",'social','social','social'],
'media':['video', 'page', 'video',
'page', 'pic',
'pic', 'video', 'page', 'video'],
'time': ['2019-04-10 19:00:00.569', '2019-04-10 00:10:00.569', '2019-04-10 00:10:20.569',
'2019-04-10 12:10:00.569','2019-04-10 11:10:00.569',
'2019-04-10 22:10:00.569','2019-04-10 14:10:00.569','2019-04-10 14:30:00.569','2019-04-10 15:10:00.569']})
Run Code Online (Sandbox Code Playgroud)
预期结果:
id ref media
0 1 social page
1 2 direct pic
2 3 social video
Run Code Online (Sandbox Code Playgroud)
您可以排序然后删除重复项:
test.sort_values(by=['id', 'time']).drop_duplicates('id').drop('time',1)
id ref media
1 1 social page
4 2 direct pic
6 3 social video
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |