You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于特定条件合并两个Pandas DataFrame

如何基于特定条件合并两个Pandas DataFrame

嘿,这个问题我太熟了!直接用merge确实卡壳,因为df2的Service列和df1的Vintage列格式不匹配,没法直接对应。不过咱们先给df2做个小改造,把里面的Vintage信息提取出来,之后合并就顺理成章了,一步步来:

第一步:提取df2中的Vintage信息

df2的Service列是类似ICE - Vintage 2025的格式,我们可以用正则表达式把里面的Vintage XXXX部分提取出来,生成一个和df1的Vintage列对应的新列:

import pandas as pd

# 先还原你的两个DataFrame(如果已经存在就跳过这部分)
df1 = pd.DataFrame({
    'BA': ['A', 'B', 'B', 'C'],
    'Product': ['foo', 'foo', 'foo', 'bar'],
    'FixedPrice': [10.00, 11.00, 12.00, 2.00],
    'Vintage': ['Vintage 2025', 'Vintage 2025', 'Vintage 2024', 'None'],
    'DeliveryPeriod': ['Mar25', 'Dec25', 'Sep25', 'Nov25']
})

df2 = pd.DataFrame({
    'Service': ['ICE - Vintage 2025', 'ICE - Vintage 2025', 'ICE - Vintage 2024', 'ICE - Vintage 2023'],
    'DeliveryPeriod': ['Mar25', 'Dec25', 'Sep25', 'Nov25'],
    'FloatPrice': [5.00, 4.00, 6.00, 1.00]
})

# 从Service列提取Vintage部分,生成新列
df2['Vintage'] = df2['Service'].str.extract(r'(Vintage \d+)')

第二步:基于匹配条件左连接合并

现在df2也有了Vintage列,我们就可以用Vintage和DeliveryPeriod作为匹配键,做左连接(how='left')来合并两个表,这样df1的所有行都会被保留:

# 只取df2中需要的列来合并,避免冗余
merged_df = pd.merge(
    df1,
    df2[['Vintage', 'DeliveryPeriod', 'FloatPrice']],
    on=['Vintage', 'DeliveryPeriod'],
    how='left'
)

第三步:填充空值为0.00

合并后,像df1中Vintage为None的行,在df2里找不到匹配项,FloatPrice会变成NaN,我们把这些空值填充成0.00就搞定了:

merged_df['FloatPrice'] = merged_df['FloatPrice'].fillna(0.00)

最终结果

执行完上面的步骤后,你就能得到想要的结果:

BA Product  FixedPrice       Vintage DeliveryPeriod  FloatPrice
0  A     foo        10.0  Vintage 2025          Mar25         5.0
1  B     foo        11.0  Vintage 2025          Dec25         4.0
2  B     foo        12.0  Vintage 2024          Sep25         6.0
3  C     bar         2.0          None          Nov25         0.0

备注:内容来源于stack exchange,提问作者iBeMeltin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:14:29