【问题标题】:Apply BeautifulSoup function to Pandas DataFrame将 BeautifulSoup 函数应用于 Pandas DataFrame
【发布时间】:2019-04-10 21:13:47
【问题描述】:

我有一个从读取 csv 获得的 Pandas DataFrame,在该文件中有我想要删除的 HTML 标签。我想用 BeautifulSoup 删除标签,因为它比使用像 <.> 这样的简单正则表达式更可靠。

我通常通过执行从字符串中删除 HTML 标记

text = BeautifulSoup(text, 'html.parser').get_text()

现在我想对 DataFrame 中的每个元素执行此操作,因此我尝试了以下操作:

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),他们说什么?如果没有这些信息,您的问题将无法解决。
  • @coldspeed 我不习惯复制确切的文本,但它基本上如下所示:head 显示了我的 11558 x 225 DataFrame 中的几个元素,其中一些是文本,其中一些是数字,例如IDs, columns 显示我的列名:id、title、text等

标签: python pandas dataframe beautifulsoup


【解决方案1】:

使用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()", 'occured at index id'),我想这可能是因为 pandas 处理了我里面的一些文本数据框作为 int 而不是字符串,知道如何解决这个问题吗?
猜你喜欢
  • 2020-07-02
  • 2012-09-26
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
  • 2015-01-25
  • 2012-10-14
相关资源
最近更新 更多