我有一个由两列组成的数据框,我想清理第二列“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
任何提示都会有帮助
问题出在
remove_html()
函数中。您很早就回来了,而且只是列表中的第一个元素。
使用下面的函数,注意
return
语句是如何在for
循环之外的函数
remove_html
只返回第一个元素您可以尝试以下代码
相关问题 更多 >
编程相关推荐