我需要从使用以下值创建的 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。
但我得到 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/