【问题标题】:Removing URL from a column in Pandas Dataframe从 Pandas Dataframe 中的列中删除 URL
【发布时间】:2018-08-23 21:04:47
【问题描述】:

我有一个小数据框,正在尝试从 Links 列中字符串的结尾。我已经尝试了以下代码,它适用于 url 独立的列。问题是,只要网址前有句子,代码就不会删除这些网址

这是数据:https://docs.google.com/spreadsheets/d/10LV8BHgofXKTwG-MqRraj0YWez-1vcwzzTJpRhdWgew/edit?usp=sharing(电子表格链接)

import pandas as pd  

df = pd.read_csv('TestData.csv')    

df['Links'] = df['Links'].replace(to_replace=r'^https?:\/\/.*[\r\n]*',value='',regex=True)

df.head()

谢谢!

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

试试这个:

import re
df['cleanLinks'] = df['Links'].apply(lambda x: re.split('https:\/\/.*', str(x))[0])

输出:

df['cleanLinks']

    cleanLinks
0   random words to see if it works now 
1   more stuff that doesn't mean anything 
2   one last try please work 

【讨论】:

    【解决方案2】:

    尝试更简洁的正则表达式:

    df['example'] = df['example'].replace(r'http\S+', '', regex=True).replace(r'www\S+', '', regex=True)
    

    在 pandas .replace() 或其他任何地方实现正则表达式之前,您应该在单个基本字符串示例上使用 re.sub() 测试模式。当遇到一个大问题时,把它分解成一个小问题。

    此外,我们可以使用 str.replace 方法:

    df['status_message'] = df['status_message'].str.replace('http\S+|www.\S+', '', case=False)
    

    【讨论】:

      【解决方案3】:

      对于 Dataframe df,可以使用更简洁的正则表达式删除 URL,如下所示:

      df = pd.read_csv('./data-set.csv')
      print(df['text'])
      
      def clean_data(dataframe):
      #replace URL of a text
          dataframe['text'] = dataframe['text'].str.replace('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', ' ')
      
      clean_data(df)
      print(df['text']);
      

      【讨论】:

        猜你喜欢
        • 2018-05-01
        • 2020-02-10
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 2012-09-25
        相关资源
        最近更新 更多