将BeautifulSoup函数应用于Pandas DataFrame

3
我有一个Pandas DataFrame,是从读取csv文件得到的,在这个文件中有HTML标签,我想要移除它们。我希望使用BeautifulSoup来移除标签,因为它比使用简单的正则表达式如<.*?>更可靠。
通常我会通过执行以下代码来从字符串中移除HTML标签:
text = BeautifulSoup(text, 'html.parser').get_text()

现在我想对我的数据框中的每个元素进行这样的操作,所以我尝试了以下方法:

df.apply(lambda text: BeautifulSoup(text, 'html.parser').get_text())

但是会返回以下错误:
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index id')

print(df.head())print(df.columns),它们在说什么?如果没有这些信息,你的问题将无法解决。 - cs95
@coldspeed,我不太舒服复制完全相同的文本,但基本上是这样的:head 显示了我的 11558 x 225 DataFrame 中的几个元素,其中一些是文本,一些是数字,例如 ID,columns 显示了我的列的名称:id、title、text 等等。 - n.st
1个回答

5

使用 applymap

举例:

import pandas as pd
from bs4 import BeautifulSoup


df = pd.DataFrame({"a": ["<a>Hello</a>"], "b":["<c>World</c>"]})
print(df.applymap(lambda text: BeautifulSoup(text, 'html.parser').get_text()))

输出:

       a      b
0  Hello  World

MoreInfo


然后我遇到了 TypeError 错误: ("object of type 'int' has no len()", 'occurred at index id'),我认为这可能是 pandas 将数据帧中的一些文本视为 int 而不是字符串处理所致,有什么解决办法吗? - n.st
@n.st df.apply(str).applymap(lambda ...) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接