如果下一行与相同模式匹配,如何删除具有模式的行?

时间:2019-10-06 14:18:31

标签: python regex pandas text text-mining

我有一个数据框,其中的一列包含每行票证的日志。这是日志的示例:

launch.json

我想删除所有没有更改的行。以下正则表达式与我正在寻找的内容RegEx101相匹配:

99645,
\Submitted',
 '\Modifications made 2015/01/01',
 'x_change0:   -->  info0',
 'y_status1:   -->  info1',
 'z_change2:   -->  info2',
 'y_change3:   -->  info3',
 '\Modifications made 2015/01/03',
 '\Modifications made 2015/01/05',
 '\Modifications made 2015/01/07',
 'w_change0:   -->  info0',
 'a_status1:   -->  info1',
 '\Modifications made 2015/01/07',
.
.
.

dataframe ['log']中每个单元格的预期结果:

pattern = '(?sm)Modifications\s*((?!Modifications\s*).)*'
re.findall(pattern, dataframe['log'])

如何删除单元格中不需要的行?或者如何用过滤后的字符串替换单元格内部的字符串?

2 个答案:

答案 0 :(得分:1)

通过@Code Maniac的RegEx解决方案解决: param3

用以下循环替换单元格字符串:

param4

答案 1 :(得分:0)

使用pd.Series.shiftstr.startswith函数的复杂过滤。

初始数据框:

In [87]: df                                                                                                    
Out[87]: 
                                  log
0   '\Modifications made 2015/01/01',
1            'change0:   -->  info0',
2            'change1:   -->  info1',
3            'change2:   -->  info2',
4            'change3:   -->  info3',
5   '\Modifications made 2015/01/03',
6   '\Modifications made 2015/01/05',
7   '\Modifications made 2015/01/07',
8            'change0:   -->  info0',
9            'change1:   -->  info1',
10  '\Modifications made 2015/01/07',

有条件的情况下删除行(添加inplace=True papam以就地修改 ):

In [88]: df.drop(df[(df.log.str.startswith("'\Modifications")) & ((df.log.shift(-1).str.startswith("'\Modificat
    ...: ions")) | (~df.log.shift(-1).str.startswith("'change", na=False)) | df.log.shift(-1).isna())].index)  
Out[88]: 
                                 log
0  '\Modifications made 2015/01/01',
1           'change0:   -->  info0',
2           'change1:   -->  info1',
3           'change2:   -->  info2',
4           'change3:   -->  info3',
7  '\Modifications made 2015/01/07',
8           'change0:   -->  info0',
9           'change1:   -->  info1',