将列表元素的关键字与pandas列匹配

时间:2018-09-18 11:11:46

标签: python python-3.x pandas dataframe

此问题是this的另一部分。所以我将其添加为新问题

如果我的数据框B类似于:

ID   category              words                   bucket_id
 1   audi                  a4, a6                  94
 2   bugatti               veyron, chiron          86
 3   mercedez              s-class, e-class        79
 4   dslr                  canon, nikon            69
 5   apple                 iphone,macbook,ipod     51
 6   finance               sales,loans,sales price 12
 7   politics              trump, election, votes  77
 8   entertainment         spiderman,thor, ironmen 88
 9   music                 beiber, rihana,drake    14
     ........              ..............
     .........             .........

我想要映射的类别及其对应的列ID作为字典。像这样:-

{'id': 2, 'term': 'bugatti', 'bucket_id': 86}
{'id': 3, 'term': 'mercedez', 'bucket_id': 79}
{'id': 6, 'term': 'finance', 'bucket_id': 12}
{'id': 7, 'term': 'politics', 'bucket_id': 77}
{'id': 9, 'term': 'music', 'bucket_id': 14}

编辑

我只想映射words列中两个逗号之间完全匹配的关键字,而不是字符串之间或其他任何单词之间。 Image

1 个答案:

答案 0 :(得分:1)

编辑:

df = pd.DataFrame({'ID': [1, 2, 3], 
                   'category': ['bugatti', 'entertainment', 'mercedez'], 
                   'words': ['veyron,chiron', 'spiderman,thor,ironmen',
                             's-class,e-class,s-class'], 
                   'bucket_id': [94, 86, 79]}) 
print (df)
   ID       category                    words  bucket_id
0   1        bugatti            veyron,chiron         94
1   2  entertainment   spiderman,thor,ironmen         86
2   3       mercedez  s-class,e-class,s-class         79

A = ['veyron','s-class','derman']

idx = [i for i, x in enumerate(df['words']) for y in x.split(',') if y in A]
print (idx)
[0, 2, 2]

L = (df.loc[idx, ['ID','category','bucket_id']]
       .rename(columns={'category':'term'})
       .to_dict(orient='r'))
print (L)

[{'ID': 1, 'term': 'bugatti', 'bucket_id': 94}, 
 {'ID': 3, 'term': 'mercedez', 'bucket_id': 79}, 
 {'ID': 3, 'term': 'mercedez', 'bucket_id': 79}]