【发布时间】:2020-11-14 00:23:38
【问题描述】:
我有两个数据框 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”列并根据以下条件分配值。
- 检查
DF1['id']值是否在DF2['id']和 DF2['documentType'] == 'Image' 中可用 - 如果是这样,请将
DF1['image1']分配给DF2['documentUrl']第一次出现的值 - 如果没有,请为
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)
【问题讨论】:
-
这将为您进行过滤
df2[df2['id'].isin(df1['id']) & df2['type']=='image']
标签: python pandas dataframe lookup