如何将groupby应用于最近的同一元素

2024-09-29 01:19:04 发布

您现在位置:Python中文网/ 问答频道 /正文

如何做到这一点?你知道吗

我能想到的是

A['new'] = A[['sth', 'content']].apply(tuple, axis=1)

A.groupby('ID')['new'].apply(list)

但事情就是这样

[[(you,A),(me,V),(me,G),(me,K),(you,D)],[(you,L),(me,A),(me,B),(me,c),(me,G)],[(me,G),(you,YT),(you,TY),(me,TY),(you,Q),(me,U)]]

有一个数据帧(让它是一个):

id      sth content
qwea    you A
qwea    me  V
qwea    me  G
qwea    me  K
qwea    you D
qfzx    you L
qfzx    me  M
qfzx    me  A
qfzx    me  B
qfzx    me  c
gg1234  me  G
gg1234  you YT
gg1234  you TY
gg1234  me  TY
gg1234  you Q
gg1234  me  U

我想要的是:

[[(you,A),(me,V,G,K),(you,D)],[(you,L),(me,A,B,c,G)],[(me,G),(you,YT,TY),(me,TY),(you,Q),(me,U)]]

Tags: youidnewcontentmeapplyytgroupby
1条回答
网友
1楼 · 发布于 2024-09-29 01:19:04

这是使用shift创建帮助键,这是问题的关键部分,之后我所做的只是将输出重新格式化为所需的格式

df['key']=(df.sth!=df.groupby('id').sth.shift()).ne(0).cumsum()
s=df.groupby(['id','key','sth']).content.apply(list).reset_index(level=2)

l=(s.sth.apply(lambda x :[x])+s.content).apply(tuple).sort_index(level=1).groupby(level=0).apply(list).tolist()

l


[[('me', 'G'), ('you', 'YT', 'TY'), ('me', 'TY'), ('you', 'Q'), ('me', 'U')], [('you', 'L'), ('me', 'M', 'A', 'B', 'c')], [('you', 'A'), ('me', 'V', 'G', 'K'), ('you', 'D')]]

相关问题 更多 >