我有一个由两列组成的数据框架,我想清理第二列'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
任何建议都会有帮助
发布于 2020-05-14 19:29:10
问题在于您的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
发布于 2020-05-14 19:37:17
函数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
https://stackoverflow.com/questions/61811152
复制相似问题