【问题标题】:How to find a match between any partial value in column A and any value column B? And extract?如何在 A 列中的任何部分值与 B 列中的任何值之间找到匹配项?并提取?
【发布时间】:2021-05-21 13:34:17
【问题描述】:

我在 pandas DataFrame 中有两列,都包含很多空值。 B 列中的某些值部分存在于 A 列的一个字段(或多个字段)中。我想检查 B 的此值是否存在于 A 中,如果存在,则分隔此值并添加为A 列中的新行

例子:

Column A   | Column B

black bear | null
black box  | null
red fox    | null
red fire   | null
green tree | null
null       | red
null       | yellow
null       | black
null       | red
null       | green

我想要以下内容:

Column A
black
bear
box
red
fire
fox
yellow
green

有人对如何获得此结果有任何提示吗?我曾尝试使用正则表达式 (re.match),但我正在努力解决我没有固定模式而是变量(即 B 列中的任何值)的事实这是我的努力:

    import re

    list_A= df['Column A'].values.tolist()
    list_B= df['Column B'].values.tolist()

    for i in list_A:
      for j in list_B:
        if i != None:
          if re.match('{j}.+', i) : 
          ...

注意:列长度超过 2500 行。

【问题讨论】:

    标签: regex list dataframe


    【解决方案1】:

    如果我正确理解您的问题,即每当在a 中找到b 时,您希望将b 的值与a 中的值拆分,然后分别存储分离的值,那么尝试一下以下?

    import re
    
    list_A = df['Column A'].values.tolist()
    list_B = df['Column B'].values.tolist()
    list_of_separated_values = []
    
    for a in list_a:
       for b in list_b:
           if b in a:
               list_of_separated_values.extend([val for val in re.split('({})'.format(b),a) if not val])
    

    【讨论】:

      【解决方案2】:

      这不是一个正则表达式问题。您将数据放在数据框中,请使用数据框功能来修复它。

      假设 data_frame 是您的 pandas DataFrame。

      # filter the DataFrame to just those with `null` in Column A
      filtered = data_frame[data_frame["Column A"].isnull()]
      # in the filtered table, assign Column B to Column A
      filtered["Column A"] = filtered["Column B"]
      # set Column B to null/None (I'm assuming you want this or this step can be skipped)
      filtered["Column B"] = None
      print(data_frame)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2017-06-05
        • 1970-01-01
        • 2012-09-04
        相关资源
        最近更新 更多