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
...
解决方案
使用 helper通过将值与累积和进行比较Series
来获取组,通过and获取计数器并重塑:task
GroupBy.cumcount
DataFrame.set_index
Series.unstack
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
推荐阅读
- visual-studio - Tfs 尝试合并错误的变更集
- abap - CL_SALV_TABLE 网格列的“F1”屏幕中缺少技术信息
- twitter - 以阿拉伯语购买特定时期和特定关键字的历史推文
- angular - angular-bootstrap-datetimepicker Angular 6 刷新视图的问题
- r - 使用 R 从 url 中提取 jpg 名称
- mysql - mysql加入不同ID的同一张表
- apache-spark - Spark 作业未显示在 Google Cloud 的 Hadoop UI 中
- arrays - 如何在一个 JSON 字段中编写一些 Lua 表?
- android - 未显示 Google AdMob 原生广告系列广告
- javascript - NodeJS + Validate.js 多个异步验证器