在.apply()for dataframes中使用for循环

2024-09-28 21:58:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除列表中的所有项目。我已经尝试使用下面的代码在pandas.apply()的上下文中遍历列表中的所有项。但是,函数remove(x)似乎只指向remove\u l中的第一项。如何确保它遍历remove\u l中的所有项?你知道吗

我知道我可以创建单独的if语句,我已经这样做了,但是我想使用for循环来实现,以防列表变长。你知道吗

remove_l = [r'[A-Za-z]+(?:\/)', r'Today, ', '-']

def remove(x):
    for phrase in remove_l:
        if re.search(phrase, x):
            if phrase == '-':
                new = x.replace(phrase, ' ')
            else: 
                new = x[re.search(phrase, x).span()[1]:].strip()
            return new 
        else: 
            return x


#check up on items 
#60, 330, 347, 411, 647
#idx = nocountries_df[nocountries_df.Name.str.contains('\/')].Name.index
nocountries_df.Name.apply(lambda x: remove(x))

Tags: 项目nameredf列表newforsearch
1条回答
网友
1楼 · 发布于 2024-09-28 21:58:01

这是一个缩进问题,当它到达第一个返回值(在for循环中)时,它返回该值:

def remove(x):
    for phrase in remove_l:
        if re.search(phrase, x):
            if phrase == '-':
                new = x.replace(phrase, ' ')
            else: 
                new = x[re.search(phrase, x).span()[1]:].strip()
            return new  # <- returns here (in first phase) 
        else: 
            return x  # <- or returns here (in first phase)

如果要在for循环之后返回,那么在for循环中更改x可能是最简单的方法:

def remove(x):
    for phrase in remove_l:
        if re.search(phrase, x):
            if phrase == '-':
                x = x.replace(phrase, ' ')
            else: 
                x = x[re.search(phrase, x).span()[1]:].strip()
    return x

相关问题 更多 >