df是非结构化的,没有列和行标题。每列都有字符串,其中有一组需要删除的模式,该模式在下面提到:
以字符串形式输入一列非结构化df:
我将被阅读===开始===我将被移除===停止===我必须再次阅读===开始===再次移除我===停止===继续阅读
需要的输出量
我要被阅读我必须再次被阅读继续阅读
在这里,无论何时发生,我都必须从字符串'=== start ==='删除为'=== stop ==='。 df有数千个条目。使用正则表达式最有效的方法是什么?
下面的代码在某列上可用,但需要很长时间才能完成。
是否有使用正则表达式的解决方案,效率最高/时间最短?
df = pd.read_excel("sample_excel.xlsx", header=None)
def removeString(df):
inf = df[0][1]
infcopy = ''
bol = False
start = '*start*'
end = '*stop*'
inf.replace('* start *',start) #in case black space between start
inf.replace('* stop *',end) #in case black space between start
for i in range(len(inf)):
if inf[i] == "*" and inf[i:i+len(start)] == start:
bol = True
if inf[i] == '*' and inf[i+1-len(end):i+1] == end:
bol = False
continue
if bol == False:
infcopy += inf[i]
df[0][1] = infcopy
答案 0 :(得分:0)
我认为它可能看起来像这样。
type=text
例如
import pandas as pd
import re
def removeString(df):
pattern = r'(?:start(.*?)stop)'
df[ColToRemove] = df[ColToRemove].apply(lambda x: re.sub(pattern, "",x))
输出:
df = pd.DataFrame({'Col1':['startjustsomethingherestop']})
然后
Col1
0 startjustsomethingherestop
输出:
pattern = r'(?:start(.*?)stop)'
df['Col1'] = df['Col1'].apply(lambda x: re.sub(pattern, "", x))
只要找到与以“ start”开始,以“ stop”结束并保留为输出的字符串匹配,此处定义的regex模式将删除所有内容