基于startswith合并DataFrame中的某些行

问题描述

我有一个DataFrame,我想在其中将某些行合并为单个行。它具有以下结构(值重复)

Index   Value
1      date:xxxx
2      user:xxxx
3      time:xxxx
4      description:xxx1
5      xxx2
6      xxx3
7      billed:xxxx
...

现在的问题是,第5列和第6列仍然属于描述,并以错误的方式分隔(整个字符串用“,”分隔)。我想将“说明”行(4)与之后的值(5,6)合并。在我的DF中,可以有1-5个必须与描述行合并的其他条目,但是该结构允许我使用startswith,因为无论必须合并多少行,端点始终是以“开帐单”开头的行。由于我是python的新手,因此尚未针对此问题编写任何代码

我的想法是(如果可能的话):

查找以“ description”开头的行→合并所有行,直到到达以“ billed”开头的行,然后停止(显然,我们保留“ billed”行)→对每行开始执行相同的操作带有“说明”

新DF应该如下:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...