2017-06-22 84 views
0

我有一个包含HTML的text列的熊猫数据框。我想获得文本,也就是去掉标签。我尝试以下做法如下:熊猫:麻烦从DataFrame剥离HTML标签列

from bs4 import BeautifulSoup 
result_df['text'] = BeautifulSoup(result_df['text']).get_text() 

然而,我最终得到这个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

我在做什么错误?

谢谢!

回答

3

试试这个:

from bs4 import BeautifulSoup 
result_df['text'] = [BeautifulSoup(text).get_text() for text in result_df['text'] ] 
1

你可以选择使用,使用apply,但我怀疑它使太大的区别的方法。

>>> import pandas as pd 
>>> data = {'a': ['<div><span>something</span></div>', '<a href="nowhere.org">erowhon</a>']} 
>>> df = pd.DataFrame(data) 
>>> df 
            a 
0 <div><span>something</span></div> 
1 <a href="nowhere.org">erowhon</a> 
>>> import bs4 
>>> df['a'] = df['a'].apply(lambda x: bs4.BeautifulSoup(x, 'lxml').get_text()) 
>>> df 
      a 
0 something 
1 erowhon 
+1

确保应用lambda函数之前删除使用“df.dropna()”的所有丢失的数据,否则你将得到“类型错误:类型的对象浮动,如果你的数据“没有LEN()”错误帧缺少数据。 – sparrow