Pandas 基于startswith合并数据帧中的某些行
我有一个数据帧,我想在其中将某些行合并为一行。它具有以下结构(值重复) 现在的问题是,第5列和第6列仍然属于描述,并且分隔错误(整个字符串以“,”分隔)。我想将“description”行(4)与后面的值(5,6)合并。在我的DF中,可以有1-5个额外的条目必须与描述行合并,但是结构允许我使用Pandas 基于startswith合并数据帧中的某些行,pandas,startswith,Pandas,Startswith,我有一个数据帧,我想在其中将某些行合并为一行。它具有以下结构(值重复) 现在的问题是,第5列和第6列仍然属于描述,并且分隔错误(整个字符串以“,”分隔)。我想将“description”行(4)与后面的值(5,6)合并。在我的DF中,可以有1-5个额外的条目必须与描述行合并,但是结构允许我使用startswith,因为无论需要合并多少行,终点总是以“billed”开头的行。由于我对python非常陌生,我还没有为这个问题编写任何代码 我的想法如下(如果可能的话): 查找以“description
startswith
,因为无论需要合并多少行,终点总是以“billed”开头的行。由于我对python非常陌生,我还没有为这个问题编写任何代码
我的想法如下(如果可能的话):
查找以“description”开头的行→ 随后合并所有行,直到到达以“billed”开头的行,然后停止(显然我们保留“billed”行)→ 对以“description”开头的每一行执行相同的操作
新的DF应该如下所示:
Index Value
1 date:xxxx
2 user:xxxx
3 time:xxxx
4 description:xxx1, xxx2, xxx3
5 billed:xxxx
...
. 您能否显示预期的
df
?添加到主位置我认为使用pandas
是不可能的。只有通过循环/迭代。你能帮我给出这样一个循环/迭代的结构吗?
Index Value
1 date:xxxx
2 user:xxxx
3 time:xxxx
4 description:xxx1, xxx2, xxx3
5 billed:xxxx
...
df = pd.DataFrame.from_dict({'Value': ('date:xxxx', 'user:xxxx', 'time:xxxx', 'description:xxx', 'xxx2', 'xxx3', 'billed:xxxx')})
records = []
description = description_val = None
for rec in df.to_dict('records'): # type: dict
# if previous description and record startswith previous description value
if description and rec['Value'].startswith(description_val):
description['Value'] += ', ' + rec['Value'] # add record Value into previous description
continue
# record with new description...
if rec['Value'].startswith('description:'):
description = rec
_, description_val = rec['Value'].split(':')
elif rec['Value'].startswith('billed:'):
# billed record - remove description value
description = description_val = None
records.append(rec)
print(pd.DataFrame(records))
# Value
# 0 date:xxxx
# 1 user:xxxx
# 2 time:xxxx
# 3 description:xxx, xxx2, xxx3
# 4 billed:xxxx