【问题标题】:Remove prefix with special characters in Python Pandas Series删除 Python Pandas 系列中带有特殊字符的前缀
【发布时间】:2020-05-02 11:38:13
【问题描述】:

如何删除以下系列中的Bale + Damon - 前缀?

import pandas as pd
x = pd.Series(['Bale + Damon - Le Mans 66', 'Bale + Damon - Ford', 'Bale + Damon - vs.', 'Bale + Damon - Ferrari'])
print(x)
0    Bale + Damon - Le Mans 66
1    Bale + Damon - Ford
2    Bale + Damon - vs.
3    Bale + Damon - Ferrari

期望的输出:

print(x2)
0    Le Mans 66
1    Ford
2    vs.
3    Ferrari

我试过x2 = x.str.replace('Bale + Damon - ',''),但它并没有改变原来的系列。

【问题讨论】:

    标签: pandas replace series


    【解决方案1】:

    你的情况

    x.str.split(' - ',n=1).str[-1]   
    
    0    Le Mans 66
    1          Ford
    2           vs.
    3       Ferrari
    dtype: object
    

    【讨论】:

    • 它确实处理了这种特殊情况,但不会处理更复杂的系列。想象一下我有很多“ - ”出现。我确实需要一个解决方案,将“Bale + Damon -”替换为“”。
    【解决方案2】:

    我们也可以使用Series.str.partition

    x.str.partition(' - ').iloc[:,-1]
    0    Le Mans 66
    1          Ford
    2           vs.
    3       Ferrari
    Name: 2, dtype: object
    

    更新

    Series.str.replaceregex=False

    x = x.str.replace('Bale + Damon - ','',regex=False)
    
    #0    Le Mans 66
    #1          Ford
    #2           vs.
    #3       Ferrari
    #dtype: object
    

    【讨论】:

    • 查看我对 YO 和 BEN_W 答案的评论。对我来说仍然看起来像一个黑客。
    • regex=False 是我需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多