从给定数据框的一列的所有行中提取粗体字母

时间:2019-11-15 15:24:53

标签: python pandas beautifulsoup

这是输入:enter image description here

0.14.1

我已经尝试过了。但无法获得所需的输出。 我有一个数据框,该数据框具有一个名为“ notes_1”的列,其中每一行的str都用粗体字母表示。我需要在同一数据帧df2中将所有粗体字母词(最后2或3个粗体词)附加到新列名“ status1”的每一行。

1 个答案:

答案 0 :(得分:1)

pd.Series.append用于连接pd.Series es;不要将一个字符串连接到pd.Series或一个字符串连接到另一个字符串。

我会使用提取粗体部分的功能对df2["notes_1"]进行pd.Series.apply

def extract_bold_words(doc):
    soup = BeautifulSoup(doc, 'html.parser')
    bold_words = soup.find_all('strong')
    string = bold_words[2].text + bold_words[3].text
    return string

df2['status1'] = df2['notes_1'].apply(extract_bold_words)

如果您喜欢for循环,则可以遍历df2['notes_1']append到列表中,最后使其成为pd.Series

status1 = []

for doc in df2['notes_1']:
    soup = BeautifulSoup(doc, 'html.parser')
    bold_words = soup.find_all('strong')
    string = bold_words[2].text + bold_words[3].text
    status1.append(string)

df2['status1'] = pd.Series(status1)