首页 > 解决方案 > 如何在 python 中清理这个 df 列,然后获取与字符串对应的行索引?

问题描述

我有以下数据集:

import pandas as pd
from bs4 import BeautifulSoup
import requests
import re

url = "https://www.ecb.europa.eu/press/key/date/2021/html/index_include.en.html"
req = requests.get(url)
soup = BeautifulSoup(req.text)
titles = soup.select(".title a")
dates = soup.select(".date")

df = pd.DataFrame({'Date': zip(dates), 'Titles': zip(titles)}) # dataframe

我想要做的是清理删除([],)文本周围的两列。然后,我想只保留第二列中包含“Lagarde”的行。这是我到目前为止所尝试的:

# to remove square and round brackets 

df.replace('([],)', '', regex=True)

# to look for rows that only have "Lagarde" in the second column

df[df['Titles'].str.contains('Lagarde', regex = False)]

在这两种情况下我都失败了,我不明白为什么。

有没有人可以帮助我?

谢谢!

标签: pythonstringdataframereplace

解决方案


您的代码的问题是您将“日期”和“标题”作为 bs4.element.Tag 对象。要将它们转换为字符串,您可以添加:

for column in df.columns:
    for i in range(len(df[column])):
        df[column][i] = df[column][i].get_text()

当你这样做时,你会得到纯字符串。然后你可以搜索你想要的任何模式。例如,如果您运行:

df[df['Titles'].str.contains('Lagarde', regex = False)]

它只返回包含“Lagarde”的行。


推荐阅读