【问题标题】:Pandas Python Regex : error: nothing to repeatPandas Python Regex:错误:无需重复
【发布时间】:2015-04-20 19:29:15
【问题描述】:

我有一个带有几个奇怪字符“*”和“-”的数据框。

import pandas as pd
import numpy as np

data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
        'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions',     'Lions', 'Lions'],
        'wins': [11, '*', 10, '-', 11, 6, 10, 4],
        'losses': [5, 8, 6, 1, 5, 10, 6, 12]}
football = pd.DataFrame(data, columns=['year', 'team', 'wins', 'losses'])

我想用 '0.00' 替换奇怪的字符,但出现错误 -

error: nothing to repeat

我知道这与正则表达式有关,但我仍然不知道如何解决这个问题。

我用来替换字符的代码:

football.replace(['*','-'], ['0.00','0.00'], regex=True).astype(np.float64)

【问题讨论】:

    标签: python regex replace pandas


    【解决方案1】:

    * 是正则表达式中的特殊字符,您必须对其进行转义:

    football.replace(['\*','-'], ['0.00','0.00'], regex=True).astype(np.float64)
    

    或使用字符类:

    football.replace([*-], '0.00', regex=True).astype(np.float64)
    

    【讨论】:

      【解决方案2】:

      football.replace(['*','-'], ['0.00','0.00'], regex=False)
      

      也就是说,对于只匹配一个或另一个字符的简单情况,不需要使用正则表达式;

      或者如果你想使用正则表达式,请注意*是一个特殊字符;如果要精确匹配 '*''-' 的值,请使用

      football.replace('^[*-]$', '0.00', regex=True)
      

      【讨论】:

      • 感谢老兄的解释。
      【解决方案3】:

      您可以在字典推导中使用列表推导来执行此操作

      >>> {key: [i if i not in {'*','-'} else '0.00' for i in values] for key, values in data.items()}
      {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
       'wins': [11, '0.00', 10, '0.00', 11, 6, 10, 4],
       'losses': [5, 8, 6, 1, 5, 10, 6, 12],
       'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions']}
      

      这将在您创建DataFrame 之前清理data

      【讨论】:

      • 感谢您的努力。
      猜你喜欢
      • 1970-01-01
      • 2021-05-01
      • 2011-09-11
      • 2019-12-27
      • 2021-07-25
      • 2019-03-26
      • 1970-01-01
      • 2018-11-25
      • 2011-04-10
      相关资源
      最近更新 更多