根据pandas中最后出现的字符串选择行

2024-06-09 09:28:09 发布

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

一个像熊猫的数据框

id   desc
1    Description
1    02.09.2017 15:00 abcd
1    this is a sample description
1    which is continued here also
1    
1    Description
1    01.09.2017 12:00 absd
1    this is another sample description
1    which might be continued here
1    or here
1
2    Description
2    09.03.2017 12:00 abcd
2    another sample again
2    and again
2
2    Description
2    08.03.2017 12:00 abcd
2    another sample again
2    and again times two 

基本上,有一个id,行以非常非结构化的格式包含信息。我想提取最后一行“description”之后的描述,并将其存储在1行中。生成的数据帧如下所示:

^{pr2}$

据我所知,我可能不得不使用groupby,但我不知道之后该怎么做。在


Tags: and数据sampleidwhichhereisanother
1条回答
网友
1楼 · 发布于 2024-06-09 09:28:09

提取最后一个Description的位置,并使用str.cat连接行

In [2840]: def lastjoin(x):
      ...:     pos = x.desc.eq('Description').cumsum().idxmax()
      ...:     return x.desc.loc[pos+2:].str.cat(sep=' ')
      ...:

In [2841]: df.groupby('id').apply(lastjoin)
Out[2841]:
id
1    this is another sample description which might...
2            another sample again and again times two
dtype: object

要有列,请使用reset_index

^{pr2}$

相关问题 更多 >