将函数应用于行中的值列表,为什么我只得到第一个结果?

2024-05-12 15:11:05 发布

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

我有一个由两列组成的数据框,我想清理第二列“tweets”。第二列“tweets”中的每个值由一个包含约100项的列表组成

我想遍历每行中的每个列表来清理文本

我的数据框示例(列表中的每个项目都是带引号的字符串):

data = ({'user_id':['324','242'],
     'tweets':[["NEWS FLASH: popcorn-flavored Tic-Tacs taste as crap as you imagine.",
                 "The 1970s is here to show us the way: https:xxxx",
                 "FB needs to hurry up and add a laugh/cry button 😬😭😓🤢🙄😱"],
               ["You don't feel like hiding in your personal cave quite so much",
                "More for Cancer https://xxxx",
                "You prefer to keep things to yourself today"]]})
df=pd.DataFrame(data)

我编写这个正则表达式是为了删除http tags

#function to remove HTML tags 
def remove_html(mylist):
    for item in mylist:
        text =re.sub(r'http\S+','',item,flags=re.MULTILINE)
        return text

我使用以下代码应用于数据框中的每一行:

df['tweets']=df['tweets'].apply(remove_html)

问题是,当我将函数应用于数据帧时,我只得到每个列表中的第一个元素。出于某种原因,该函数只返回第一个元素

我得到的输出:

0    NEWS FLASH: popcorn-flavored Tic-Tacs taste as crap as you imagine.
1    You don't feel like hiding in your personal cave quite so much     
Name: tweets, dtype: object

任何提示都会有帮助


Tags: to数据inyoudf列表dataas
2条回答

问题出在remove_html()函数中。
您很早就回来了,而且只是列表中的第一个元素。
使用下面的函数,注意return语句是如何在for循环之外的

def remove_html(mylist): 
    return_list = [] 
    for item in mylist: 
        text = re.sub(r'http\S+','',item,flags=re.MULTILINE) 
        return_list.append(text)  
    return return_list 

函数remove_html只返回第一个元素

您可以尝试以下代码

#function to remove HTML tags 
def remove_html(mylist):
    t = []
    for item in mylist:
        text =re.sub(r'http\S+','',item,flags=re.MULTILINE)
        t.append(text)
    return t

相关问题 更多 >