【问题标题】:Regex with columns pandas带有熊猫列的正则表达式
【发布时间】:2016-12-31 17:10:28
【问题描述】:

我的问题是如何使用re 替换数据框中包含的字符串:

当我使用re.sub() 时,它给了我一个错误:

p = re.compile('New')
p.sub('old', df['Col1'])

另外,我尝试使用 for 循环,但输出出乎意料,并在所有其他行中显示第一行的值:

for i in df['Col1']:
    p.sub('old', i)
    print(i)

我确定我错过了什么。

【问题讨论】:

    标签: python regex pandas dataframe series


    【解决方案1】:

    我认为你可以使用str.replace,它也适用于regex

    df = pd.DataFrame({'Col1':['sss old','dd','old']})
    print (df)
          Col1
    0  sss old
    1       dd
    2      old
    
    df.Col1 = df.Col1.str.replace('old','new')
    print (df)
          Col1
    0  sss new
    1       dd
    2      new
    

    【讨论】:

    • 还有一个问题:当我想将 re 与 str.startswith 一起使用时。它返回所有值 false。即:df.col1.str.startswith('(N|n)ew'),我错过了什么吗?
    • str.startswith 不适用于正则表达式。
    猜你喜欢
    • 2021-08-22
    • 2015-11-18
    • 2020-02-15
    • 2019-10-19
    • 2020-11-14
    • 2020-01-05
    • 2018-04-30
    • 2019-05-26
    相关资源
    最近更新 更多