python - 如何从 Pandas DataFrame 中提取 URL?

标签 python regex pandas dataframe

我需要从使用以下值创建的 DataFrame 列中提取 URL

creation_date,tweet_id,tweet_text
2020-06-06 03:01:37,1269102116364324865,#Webinar: Sign up for @SumoLogic's June 16 webinar to learn how to navigate your #Kubernetes environment and unders… https://stackoverflow.com/questions/42237666/extracting-information-from-pandas-dataframe
2020-06-06 01:29:38,1269078966985461767,"In this #webinar replay, @DisneyStreaming's @rothgar chats with @SumoLogic's @BenoitNewton about how #Kubernetes is… https://stackoverflow.com/questions/46928636/pandas-split-list-into-columns-with-regex

列名 tweet_text 包含 URL。我正在尝试以下代码。

df["tweet_text"]=df["tweet_text"].astype(str)
pattern = r'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)'

df['links'] = ''
df['links']= df["tweet_text"].str.extract(pattern, expand=True)

print(df)

我正在使用 this question 的答案中的正则表达式并且它匹配两行中的 URL。 screenshot 但我得到 NaN 作为新列 df['links]' 的值。我也尝试过 this question 的第一个答案中提供的解决方案, 这是

df['links']= df["tweet_text"].str.extract(pattern, expand=False).str.strip()

但是我得到以下错误

AttributeError: 'DataFrame' object has no attribute 'str'

最后我使用 df['links'] = '' 创建了一个空列,因为我得到了 ValueError: Wrong number of items passed 2, placement implies 1错误。如果那是相关的。 有人可以帮我吗?

最佳答案

主要问题是您的 URL 模式包含捕获组,而您需要非捕获组。您需要将模式中的所有 ( 替换为 (?:

但是,这还不够,因为 str.extract 需要模式中的捕获组,以便它可以返回任何值。因此,您需要用一个捕获组来包装整个模式。

你可以使用

pattern = r'(https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}[-a-zA-Z0-9()@:%_+.~#?&/=]*)' 

请注意,+ 不是在字符类中转义所必需的。另外,不需要在字符类中使用//,一个/就够了。

关于python - 如何从 Pandas DataFrame 中提取 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62229836/

相关文章:

python - Django基于变量(str)的动态过滤器

python - windows 10下安排python脚本加载数据到BigQuery

javascript - 如何在正则表达式中捕获n个组,以便我可以在js中替换它们

regex - 对 Get-Help 输出 : how to use Regex to select exact string that starts with a hyphen(-) and ends with an alphabet 进行着色

java - Java正则表达式中的匹配字符

python - 使用类似维度转换行值

python - 如何在 python 3 中删除字符串中的最后一个字符

python - sqlalchemy,说小数没有定义?

python - 仅在数据框中提取最小值

python - reshape Pandas 数据框分组变量