Python 提取数据帧中多个字之间的子字符串

Python 提取数据帧中多个字之间的子字符串,python,string,pandas,numpy,dataframe,Python,String,Pandas,Numpy,Dataframe,我有一个pandas数据框,需要根据以下条件从列的每一行提取子字符串 我们从“一”、“一次我”、“他”开始,到“好”、“一”、“好”结束。 子字符串前面应该有start_列表中的任何元素。 子字符串可以由end_列表的任何元素继承。 当“开始”列表的任何元素可用时,应在不存在“结束”列表元素的情况下提取后续子字符串。 示例问题: 预期结果: 我想这应该对你有用。这个解决方案当然需要Pandas和内置的库工具 功能:删除前序 此函数将单词start_list和str string的集合作为输入。它

我有一个pandas数据框,需要根据以下条件从列的每一行提取子字符串

我们从“一”、“一次我”、“他”开始,到“好”、“一”、“好”结束。 子字符串前面应该有start_列表中的任何元素。 子字符串可以由end_列表的任何元素继承。 当“开始”列表的任何元素可用时,应在不存在“结束”列表元素的情况下提取后续子字符串。 示例问题:

预期结果:


我想这应该对你有用。这个解决方案当然需要Pandas和内置的库工具

功能:删除前序

此函数将单词start_list和str string的集合作为输入。它查看start_列表中是否有任何项在字符串中,如果是,则只返回在所述项之后出现的字符串片段。否则,它将返回原始字符串

功能:删除成功者

此函数与第一个函数非常相似,只是它只返回在end_列表中的项之前出现的字符串片段

功能:适用于

如何实际运行上述函数?apply方法允许您在数据帧或序列上运行复杂函数,但它将根据您是在DF上运行还是在S上运行,分别查找整行或单个值作为输入

此函数以要运行的函数和要检查的单词集合作为输入,我们可以使用它运行上述两个函数:

def to_apply(func, words_to_check):
    return functools.partial(func, words_to_check)
如何运行

最后一步是从子字符串列中删除不受筛选影响的项:

def final_cleanup(row):
    if len(row['a']) == len(row['substring']):
        return ''
    else:
        return row['substring']

df['substring'] = df.apply(final_cleanup, axis=1)
结果


希望这能起作用。

非常感谢您的帮助。这段代码工作得非常好。非常感谢您在短时间内提供的帮助。谢谢!没问题,很高兴听到。如果你能接受答案,那就太好了。对不起,我是堆栈溢出新手,因此不知道“接受”按钮。我试图投一张“赞成票”,但系统提示我回答说我没有最低声誉。对不起,非常感谢。没问题!!非常感谢你。
def remove_preceders(start_list, string):
    for word in start_list:
        if word in string:
            string = string[string.find(word) + len(word):]
    return string
def remove_succeeders(end_list, string):
    for word in end_list:
        if word in string:
            string = string[:string.find(word)]
    return string
def to_apply(func, words_to_check):
    return functools.partial(func, words_to_check)
df['no_preceders'] = df.a.apply(
                         to_apply(remove_preceders, 
                                 ('one', 'once I', 'he'))
                               )
df['no_succeders'] = df.a.apply(
                          to_apply(remove_succeeders, 
                                  ('fine', 'one', 'well'))
                               )
df['substring'] = df.no_preceders.apply(
                          to_apply(remove_succeeders, 
                                  ('fine', 'one', 'well'))
                               )
def final_cleanup(row):
    if len(row['a']) == len(row['substring']):
        return ''
    else:
        return row['substring']

df['substring'] = df.apply(final_cleanup, axis=1)