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

如何使用另一pandas.DataFrame数据填充目标DataFrame列?

Solution Using Pandas Merge

To get your desired result, you'll use pandas' merge() function to join the two DataFrames based on matching values between second_key (from the first DataFrame) and key (from the second DataFrame). Here's a straightforward implementation:

Step 1: Set Up Your DataFrames

First, let's recreate the DataFrames you provided:

import pandas as pd

# First DataFrame
first_df = pd.DataFrame({
    'first_key': [0, 0, 0, 0, 0],
    'second_key': [1, 1, 2, 3, 3]
})

# Second DataFrame
second_df = pd.DataFrame({
    'key': [1, 2, 3],
    'status': ['good', 'bad', 'good']
})

Step 2: Merge and Clean Up

Use pd.merge() to combine the DataFrames, then remove the redundant key column that comes along with the merge:

merged_df = pd.merge(
    first_df,
    second_df,
    left_on='second_key',
    right_on='key',
    how='left'  # Keeps all rows from the first DataFrame
).drop('key', axis=1)

Step 3: Check the Result

Printing merged_df will give you exactly the output you want:

first_key  second_key status
0          0           1   good
1          0           1   good
2          0           2    bad
3          0           3   good
4          0           3   good

Quick Explanation

  • left_on='second_key' and right_on='key': Tells pandas to match rows where the value in second_key (from the left DataFrame) equals the value in key (from the right DataFrame).
  • how='left': Ensures every row from your original first DataFrame is preserved, even if there's no matching entry in the second DataFrame (in such cases, status would show NaN).
  • .drop('key', axis=1): Removes the duplicate key column added during the merge, leaving only the columns you need.

内容的提问来源于stack exchange,提问作者Sergey Malashenko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:33:07