【问题标题】:Python Pandas - replace based on regex - ignoring rest of the values - regex based vlookup in pythonPython Pandas - 基于正则表达式替换 - 忽略其余值 - python 中基于正则表达式的 vlookup
【发布时间】:2020-11-11 14:59:34
【问题描述】:

我有一个简单的任务,我正在尝试做,但到目前为止还没有成功运行它。 我得到了一个数据框df 和一个我想从数据框df 中检查的正则表达式列表,以及我想在正则表达式匹配的位置插入my_regex_dict 中的相应值。

df = pd.DataFrame ( ['a100','b110','c200','100a'],columns = ["A"])
my_regex_dict = {'.*a.*':'apple', '.*b.*':'ball'}

数据如下

df:
    A
0   a100
1   b110
2   c200
3   100a

my_regex_dict:
{'.*a.*': 'apple', '.*b.*': 'ball'}

将 dict 转换为适合我在 dict 上执行的 pandas 中的 .replace 函数。

my_regex_dict =  {rf'\b{k}\b': v for k, v in my_regex_dict.items()}

现在字典看起来如下

my_regex_dict:
{'\\b.*a.*\\b': 'apple', '\\b.*b.*\\b': 'ball'}

我要做的就是检查 A 列中的每个值,对照字典,如果正则表达式匹配,给我相应的值,但是没有,给我空白。

我已经完成了以下操作,这是有效的,但做了一些额外的事情

df["E"] = df.A.str.lower().replace(  dict_regex,regex = True)

这是我得到的结果

     A       E
0   a100    apple
1   b110    ball
2   c200    c200
3   100a    apple

我想要的是跟随,即针对 c200 的空白或 NULL。

         A       E
0   a100    apple
1   b110    ball
2   c200    
3   100a    apple

任何帮助都将受到高度评价。谢谢。

【问题讨论】:

    标签: python regex pandas replace


    【解决方案1】:

    你可以replace只匹配值:

    s = df.A.str.lower()
    m = s.str.contains('|'.join(my_regex_dict.keys()))
    df["E"] = s[m].replace(my_regex_dict,regex = True)
    print (df)
          A      E
    0  a100  apple
    1  b110   ball
    2  c200    NaN
    3  100a  apple
    

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2011-05-14
      • 2021-09-04
      • 2020-10-16
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多