使用字典和模式匹配填充列值

问题描述 投票:0回答:1

我正在研究对信用卡交易进行分类。现在我正在使用字典与 np.select() 结合使用,如下所示:

    def cat_mapper(frame, targ_col, cat_col):
    
        category_retailers = {'Online Shopping':['amazon','amzn mktp', 'target.com'],
                              'Wholesale Stores': ['costco', 'target'],
                             }
        cond = [frame[targ_col].str.contains('|'.join(category_retailers['Online Shopping']),regex=True,case=False),
                frame[targ_col].str.contains('|'.join(category_retailers['Wholesale Stores']),regex=True,case=False),
               ]

        choice = ['Online Shopping',
                  'Wholesale Stores'
                 ]
       
        default_cond = frame[cat_col]

        frame[cat_col] = np.select(cond, choice, default_cond)
        return frame

其中frame参数是数据帧,targ_col参数是带有事务描述或名称的描述列,cat_col参数是将包含事务类别的类别列。

基本前提是检查交易描述列中字典值是否部分匹配,如果描述中存在部分匹配,则将相应的字典键分配给类别列。

上述块的功能没有问题,但是必须定义字典值,然后将字典值与 np.select 的相应条件和选择进行匹配,因此存在一些冗余。

有没有一种方法可以将事务描述与字典中的值列表进行模式匹配,并将字典键分配给类别列,而不使用 np.select 作为中介?

我假设我可以使用嵌套循环,但即使这样似乎也很冗长。有没有更雄辩的方法来达到相同的结果。

示例数据框:

data_dict {'Description': ['amazon 345689','amzn mkpt online 7765','amazon 4444','costco location','Wholefoods'],
           'Category':['Nan','Nan','Nan','Nan','Groceries']
          }
pd.Dataframe(data=data_dict)

提前致谢,如果您需要我提供任何其他详细信息,请告诉我

python pandas dataframe dictionary
1个回答
0
投票

您可以通过使用列表理解来计算条件并利用字典键/值来重构代码:

def cat_mapper(frame, targ_col, cat_col):
    category_retailers = {'Online Shopping':['amazon','amzn mktp', 'target.com'],
                          'Wholesale Stores': ['costco', 'target'],
                         }
    cond = [frame[targ_col].str.contains('|'.join(val),regex=True,case=False)
            for val in category_retailers.values()]

    frame[cat_col] = np.select(cond, list(category_retailers), frame[cat_col])
    return frame

cat_mapper(df, 'Description', 'Category')

输出:

             Description          Category
0          amazon 345689   Online Shopping
1  amzn mkpt online 7765               NaN  # not matching because of typo
2            amazon 4444   Online Shopping
3        costco location  Wholesale Stores
4             Wholefoods         Groceries

使用的输入:

data_dict = {'Description': ['amazon 345689','amzn mkpt online 7765','amazon 4444','costco location','Wholefoods'],
             'Category':['Nan','Nan','Nan','Nan','Groceries']
          }
df = pd.DataFrame(data=data_dict).replace('Nan', float('nan'))
© www.soinside.com 2019 - 2024. All rights reserved.