【问题标题】:Searching for a substring in a dataframe and replacing it在数据框中搜索子字符串并替换它
【发布时间】:2017-07-04 13:50:44
【问题描述】:

我有一种情况,其中创建了虚假数据,我正在尝试清理它。

例如...

www.one@foxturn.com/!ut/5 #RealLink
www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD # System adds junks to it
www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf # System adds junks to it

我正在尝试通过删除 !ut 之后的所有内容来清理它

到目前为止我已经尝试过:

SPA_MX = Mexico['Page URL'].str.startswith("http://www.www.one@foxturn.com/ut1")

但这会返回一个布尔值。

我想就实现这一目标的最有效方法提出建议。

【问题讨论】:

    标签: python string python-3.x pandas dataframe


    【解决方案1】:

    您可以在列上使用apply 执行此操作,然后使用find 返回模式的索引并在找到时对str 进行切片:

    In[69]:
    
    df['url'].apply(lambda x: x[:x.find('!ut') + 3] if x.find('!ut') != -1 else x)
    
    Out[69]: 
    0                             www.one@foxturn.com/!ut
    1           www.one@foxturn.com/ut1/5_RTFDEERERTGFEFD
    2    www.one@foxturn.com/ut1/5_dvkerfddfrejermsdkasmf
    Name: url, dtype: object
    

    【讨论】:

    • 谢谢你,..我想保留 !ut 但在此之后放弃一切..我怎样才能做到这一点?即...所有链接看起来都一样。
    • 查看更新,不幸的是,由于位置是可变的,我认为不使用 apply 没有很好的方法,因为您不能对字符串列进行可变长度切片跨度>
    【解决方案2】:
    my_string="www.one@foxturn.com/!ut/5"
    final =  my_string.split("!ut")[0]
    

    输出:

    www.one@foxturn.com/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-07
      • 2015-04-11
      • 1970-01-01
      • 2020-07-09
      • 2011-04-13
      • 2015-10-03
      • 2017-01-10
      • 2015-09-25
      相关资源
      最近更新 更多