问题描述
tags
0 label
0 document
0 text
0 paper
0 poster
...
21600 wood
21600 hot tub
21600 tub
21600 terrace
21600 blossom
还有另一个数据框 df2 ,该数据框具有到df中存在的标签的映射,该标签映射到列名“名称”。
name iab
0 abies Nature and Wildlife
1 absinthe Food & Drink
2 abyssinian Pets
3 accessories Style & Fashion
4 accessory Style & Fashion
... ... ... ... ...
1595 rows × 4 columns
本质上,这个想法是在df2中搜索与df1中的标签相对应的“名称”列,以找到对应的“ iab”映射,并输出包含两列的CSV-标签及其对应的“ iab”映射。 / p>
输出看起来像这样:
tags iab
0 label <corresponding iab mapping
to 'name' found in df2>
0 document
0 text
0 paper
0 poster
...
21600 wood
21600 hot tub
21600 tub
21600 terrace
21600 blossom
我需要帮助来实现这一目标。预先谢谢你!
注意:
我尝试过的是
df_iab[df_iab['name'].isin(df['image_CONTAINS_OBJECT'])]
但这只会将df2缩小为与“标签”匹配的“ iab”,而不会真正执行搜索并映射找到的值。
解决方法
合并:
new_df = df1.merge(df2,how='left',left_on='tags',right_on='name')
,
另一种方法是使用.map
将iab
的详细信息从df2
转移到df1
。
df1['iab']=df1.tags.map(dict(zip(df2.name,df2.iab)))
工作方式
#come up with a dictionary of name and `iab` in `df2`.
d=dict(zip(df2.name,df2.iab))
# Map the dict to df1 using the tag column
df1.tags.map(d)