【问题标题】:Finding regular expression in a range in python dataframe在python数据框中的范围内查找正则表达式
【发布时间】:2019-12-21 05:05:01
【问题描述】:

我遇到了问题

我有一个名为雇主的数据框,如下所示:

employer
------------
wings brand activation i pvt ltd
hofincons infotech &industrial services pvt .ltd
bharat fritz werner bangalore
kludi rak indpvt ltd.

另一个将雇主名称映射到看起来像的类别的数据框(称为 pincode):

Index   Name                                    FINAL_CATEGORY
68781   central board of excise and customs     cat b
68782   c a g hotels pvt ltd                    cat b
68783   avaneetha textiles pvt ltd              cat a
68784   trendy wheels pvt ltd                   cat a+
68785   wings brand activations india pvt ltd   cat b

现在我想模拟类似的东西:

pincode[pincode['Compnay Name'].str.contains('wings brand activation i pvt ltd')]

Compnay Name    FINAL_CATEGORY
____________________________________

pincode[pincode['Compnay Name'].str.contains('wings brand activation i pvt')]

Compnay Name    FINAL_CATEGORY
____________________________________

pincode[pincode['Compnay Name'].str.contains('wings brand activation i')]


Compnay Name    FINAL_CATEGORY
____________________________________

pincode[pincode['Compnay Name'].str.contains('wings brand activation')]

        Name                                    FINAL_CATEGORY
68785   wings brand activations india pvt ltd   cat b

如您所见,对于每个字符串,我从字符串末尾开始减少长度直到最后一个空格,然后进行搜索。

以上内容需要与(我认为是正则表达式)一起循环。因此,对于雇主表中的每个条目,它都会搜索整个密码范围并找出最接近的匹配项。如果没有,则返回 nan。

提前谢谢,因为这个问题很难用语言表达,请寻求任何澄清。

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    您可以使用如下迭代方法:

    def find_substr(employer, pincode):
        employer = employer.set_index("employer")
        for words in employer.index.map(str.split):
            length = len(words)
            found = False
            while length > 0 and not found:
                substr = ' '.join(words[:length]).replace('(', '\(')
                mask = pincode.Name.str.contains(substr)
                if mask.any():
                    employer.loc[' '.join(words), 'cat'] = pincode.loc[mask, 'FINAL_CATEGORY'].values[0]
                    found = True
                length -= 1
        employer = employer.reset_index()
        return employer
    
    employer = find_substr(employer, pincode)
    print(employer)
    
                                               employer    cat
    0                  wings brand activation i pvt ltd  cat b
    1  hofincons infotech &industrial services pvt .ltd    NaN
    2                     bharat fritz werner bangalore    NaN
    3                              kludi rak indpvt ltd    NaN
    

    【讨论】:

    • ValueError Traceback(最近一次调用最后一次) in ----> 1 个雇主 = find_substr(data, pincode) in find_substr(employer, pincode) 8 mask = pincode.Name.str.contains(substr) 9 if mask.any(): ---> 10 employee.loc[' '.join(words), 'cat' ] = pincode.loc[mask, 'FINAL_CATEGORY'].values 11 found = True
    • ValueError:形状不匹配:形状(30,)的值数组无法广播到形状(1373,)的索引结果
    • 您必须有多行对应匹配子字符串。如果你是肯定的只有一个类别,你可以采取....values[0]
    • 是的,先生,可以有多个值,pincode是唯一的,而雇主可以有多个值(多个雇员有同一个雇主),基本上需要进行键值配对。
    • 好的,但是一个雇主只映射到一个类别?如果是这样,只需像这样添加一个索引器:pincode.loc[mask, 'FINAL_CATEGORY'].values[0]
    【解决方案2】:

    这是一种方法。

    首先将您的引脚 df 转换为将字符串映射到相应类别的字典。然后使用双重列表推导创建员工数据框的 cat 列,以记录与他的姓名匹配的所有类别:

    # Example df
    employer = pd.DataFrame({"employer":["wings brand activation i pvt ltd", "bharat fritz werner bangalore"]})
    pins = pd.DataFrame({"Name":["trendy wheels pvt ltd", "wings brand activation i pvt ltd"], "FINAL_CATEGORY":["cat a+", "cat b"]}) 
    
    dict_pins = dict(zip(pins['Name'], pins['FINAL_CATEGORY']))
    employer['cat'] = [[dict_pins[key] for key in dict_pins.keys() if x in key] for x in employer['employer']]
    

    输出:

                               employer      cat
    0  wings brand activation i pvt ltd  [cat b]
    1     bharat fritz werner bangalore       []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2019-01-25
      • 2015-06-20
      • 1970-01-01
      • 2019-10-15
      相关资源
      最近更新 更多