查找数据帧(字符串列表)和字典键(元组)之间的部分匹配

时间:2017-08-04 15:01:03

标签: python pandas dictionary

我有一个字典,其中每个键都是一个元组列表,如下所示:

[in]
product_combos = dict()
for i in training_df['product_id']:
    key = tuple(i)
    if key in product_combos:
        product_combos[key] += 1
    else:
        product_combos[key] = 1

print(product_combos)

[out]
{('P06', 'P09'): 36340, 
('P01', 'P05', 'P06', 'P09'): 10085, 
('P01', 'P06'): 36337, 
('P01', 'P09'): 49897, 
('P02', 'P09'): 11573

如何找到这些键与这样组织的数据帧列之间的部分匹配(其中product_id列中的每一行都是字符串列表):

[in]
# Use the arrays to create a dataframe
testing_df =pd.DataFrame(test_array,columns=['transaction_id','product_id'])

# Split the product_id's for the testing data
testing_df.set_index(['transaction_id'],inplace=True)

testing_df['product_id'] = testing_df['product_id'].apply(lambda row: row.split(','))
print(testing_df.head(n=10))

[out]
                     product_id
transaction_id                 
001                       [P01]
002                  [P01, P02]
003             [P01, P02, P09]
004                  [P01, P03]
005             [P01, P03, P05]

我想做这样的事情:partial match of dictionary keys

但是比较应该在字典的键和数据帧的行之间。

1 个答案:

答案 0 :(得分:0)

你可以使用申请。

  transaction_id product_id            
0  001                          ['P01']
1  002                   ['P01', 'P02']
2  003            ['P01', 'P02', 'P09']
3  004                   ['P01', 'P03']
4  005            ['P01', 'P03', 'P05']

keys = {('P06', 'P09'): 36340, 
 ('P01', 'P05', 'P06', 'P09'): 10085, 
('P01', 'P06'): 36337, 
('P01', 'P09'): 49897, 
('P02', 'P09'): 11573

df.product_id.apply( lambda x:[ v for k,v in keys.iteritems() if any( i in x for i in k)][:len(x)+1])

0                  [10085, 36337]
1           [10085, 11573, 36337]
2    [10085, 11573, 36337, 36340]
3           [10085, 36337, 49897]
4           [10085, 36337, 49897]