【问题标题】:str.replace starting from the back in pandas DataFramestr.replace 在 pandas DataFrame 中从后面开始
【发布时间】:2018-01-28 09:13:10
【问题描述】:

我有两列像这样:

                                       string                    s
0    the best new york cheesecake new york ny             new york
1               houston public school houston              houston

我想删除string 中最后出现的s。对于上下文,我的 DataFrame 有数十万行。我知道str.replacestr.rfind,但没有什么能实现两者的理想组合,而且我在即兴解决方案方面处于空白。

提前感谢您的帮助!

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    您可以使用rsplitjoin

    df.apply(lambda x: ''.join(x['string'].rsplit(x['s'],1)),axis=1)
    

    输出:

    0    the best new york cheesecake  ny
    1              houston public school 
    dtype: object
    

    编辑:

    df['string'] = df.apply(lambda x: ''.join(x['string'].rsplit(x['s'],1)),axis=1).str.replace('\s\s',' ')
    
    print(df)
    

    输出:

                                string         s  third
    0  the best new york cheesecake ny  new york      1
    1           houston public school    houston      1
    

    【讨论】:

    • 非常好。如果最后一次出现在字符串中间,您能否添加replace 或类似函数来消除拆分后留下的双倍空格?
    • @vealkind 是的。 df.apply(lambda x: ''.join(x['string'].rsplit(x['s'],1)),axis=1).str.replace('\s\s',' ')
    • 我添加了第三列,这似乎只保留了string 列。有没有办法同时保留其他列?
    • 我的荣幸。编码愉快!
    【解决方案2】:

    选项 1
    带理解的矢量化rsplit

    from numpy.core.defchararray import rsplit
    
    v = df.string.values.astype(str)
    s = df.s.values.astype(str)
    
    df.assign(string=[' '.join([x.strip() for x in y]) for y in rsplit(v, s, 1)])
    
                                string         s
    0  the best new york cheesecake ny  new york
    1           houston public school    houston
    

    选项 2
    使用re.sub
    此处的正则表达式查找来自 s 且后面没有另一个相同值的值。

    import re
    
    v = df.string.values.astype(str)
    s = df.s.values.astype(str)
    f = lambda i, j: re.sub(r' *{0} *(?!.*{0}.*)'.format(i), ' ', j).strip()
    
    df.assign(string=[f(i, j) for i, j in zip(s, v)])
    
                                string         s
    0  the best new york cheesecake ny  new york
    1            houston public school   houston
    

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 2016-11-02
      • 1970-01-01
      • 2021-09-13
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2019-09-30
      相关资源
      最近更新 更多