Pandas:添加新列并按条件从另一个数据框中分配值

Pandas: Add new column and assigning value from another dataframe by condition

我有两个数据帧 DF1 和 DF2

DF1:

id      product
a       a
b       b
c       c
d       d

DF2:

id      documentType      documentUrl
a       3D                https://...a.dxf
a       Image             https://...a.jpg
b       PDF               https://...b.pdf
b       Image             https://...b.jpg
b       Image             https://...b2.jpg
c       PDF               https://...c.pdf

我想在 DF1 中创建一个列“image1”并根据以下条件赋值。

  1. 检查 DF1['id'] 值是否在 DF2['id'] 和 DF2['documentType'] 中可用 == 'Image'
  2. 如果是,请将 DF1['image1'] 中的值分配给 DF2['documentUrl'] 中最先出现的值
  3. 如果没有,分配 DF1['image1'] 一个占位符 URL 'https://...no_image.jpg'

所以输出应该是这样的:

id      product      image1
a       a            https://...a.jpg
b       b            https://...b.jpg
c       c            https://...no_image.jpg
d       d            https://...no_image.jpg

不确定如何解决这个问题,但有一些想法:

- 加入/合并是我的第一个想法,但如何处理条件?

- 也许映射/应用检查条件的函数

DF1['image1'] = DF1['id'].map(DF2.set_index('id')['documentUrl'], condition)

您可以先筛选:

s = (DF2.loc[DF2.documentType=='Image']
        .drop_duplicates('id')
        .set_index('id')['documentUrl']
    )
DF1['image'] = DF1['id'].map(s)

输出:

  id product             image
0  a       a  https://...a.jpg
1  b       b  https://...b.jpg
2  c       c               NaN
3  d       d               NaN