基于上一行向新列添加数据

2024-06-02 09:10:36 发布

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

df
     type  content
1    task   buy xbox
2    task   buy fruit from supermarket
3    note   orange with squash\buy if cheap
4    note   apple
5    task   buy sunglassess

注释指的是它正上方的任务。如何操纵df以获得以下df? 预期产出:

         task                       comment1             comment2
1     buy xbox
2     buy fruit from supermarket   orange with squash     apple
                                   buy if cheap
3     buy sunglassess
...

Tags: fromappledftaskifwithbuysquash
1条回答
网友
1楼 · 发布于 2024-06-02 09:10:36

使用helper Series通过task通过比较值与累计和来获取组,通过^{}获取计数器,并通过^{}^{}来重塑形状:

s = df['type'].eq('task').cumsum()
g = df.groupby(s).cumcount()

df1 = (df.set_index([s, g])['content']
         .unstack(fill_value='')
         .add_prefix('comment')
         .rename(columns={'comment0':'task'})
         .reset_index(drop=True))
         
print (df1)
                         task                        comment1 comment2
0                    buy xbox                                         
1  buy fruit from supermarket  orange with squasuy if cheap    apple
2             buy sunglassess                                         

相关问题 更多 >