【问题标题】:Pandas: Add new column and assigning value from another dataframe by conditionPandas:添加新列并按条件从另一个数据框中分配值
【发布时间】: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”列并根据以下条件分配值。

  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)

【问题讨论】:

  • 这将为您进行过滤df2[df2['id'].isin(df1['id']) & df2['type']=='image']

标签: python pandas dataframe lookup


【解决方案1】:

你可以先过滤:

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

【讨论】:

  • 谢谢这对我有用 - 为了避免 NaN 值并设置自定义的无图像 url,我将您的解决方案与 .fillna() DF1['image'] = DF1['id'].map(s).fillna('https://...no_image.jpg') 链接在一起
猜你喜欢
  • 2022-10-23
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 2019-10-14
相关资源
最近更新 更多