我有一個數據框df1,如下所示,它有一個標簽列表。 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”。 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”映射。輸出看起來像這樣: 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”,但不會真正執行搜索并映射找到的值。
2 回答

慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
合并:
new_df = df1.merge(df2, how='left', left_on='tags', right_on='name')

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
另一種方法是使用.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)
添加回答
舉報
0/150
提交
取消