python - 如何在 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)]
在这两种情况下我都失败了,我不明白为什么。
有没有人可以帮助我?
谢谢!
解决方案
您的代码的问题是您将“日期”和“标题”作为 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”的行。
推荐阅读
- javascript - JavaScript:搜索功能,使用搜索栏输入删除无序列表元素
- node.js - 如何使用 nodejs 从 pouchdb 响应中访问值?
- python - 为什么 `python3 -m pip install .` 不安装我的包,但 `pip3 install .` 可以?
- c# - 在asp.net Core之前水平合并后如何垂直合并两个Cell?
- javascript - 试图将 jquery 转换为 vanilla js
- r - 如何将正则表达式与 dplyr 的选择辅助函数一起使用
- visual-studio-code - 从 WSL 在 VS Code 中打开本地文件夹
- php - PHP 没有应用正则表达式来检查空字符串
- python - 根据 Python 中的值的总和迭代字典
- wpf - WPF - 如何通过半透明图层创建点击