【问题标题】:Find partial matches between a dataframe (list of strings) and dictionary keys (tuples)查找数据框(字符串列表)和字典键(元组)之间的部分匹配
【发布时间】:2017-08-04 15:01:02
【问题描述】:

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

[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

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

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    你可以使用申请。

      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]
    

    【讨论】:

    • 如何限制比较的长度?例如,如果testing_dfproduct_id 的# 为2,我只想返回长度为3 的部分匹配项。
    • AttributeError: 'dict' object has no attribute 'iteritems'
    • @zsad512 for iteritems,试着换成items
    • @zsad512 你能给我一个你需要的例子吗
    • 例如:如果testing_df 中的product_id 是'P01',那么我只想要长度为2 等的product_combos 键。
    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 2020-11-28
    • 2017-04-02
    • 2019-03-16
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多