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

如何按ID将df1中的NA值替换为df2对应列的值?

Replace NA Values in df1's Count Column with df2's Corresponding Values (Matching by ID)

Got it, let's tackle this problem step by step. Assuming you're using pandas (the standard library for DataFrame work in Python), here are two simple, effective solutions to get your target df3:

Solution 1: Use fillna() with map()

This method directly maps df2's Count values to df1's NA entries by ID, keeping non-NA values in df1 intact.

First, let's replicate your sample data (to test the solution):

import pandas as pd

# Sample df1
df1 = pd.DataFrame({
    'ID': [11, 22, 33, 44, 55, 66, 77],
    'Count': [345, 456, 786, 765, None, 888, None]
})

# Sample df2
df2 = pd.DataFrame({
    'ID': [11, 22, 33, 44, 55, 66, 77],
    'Count': [536, 654, 786, 999, 890, 111, 654]
})

Now run the core replacement logic:

# Create a lookup Series from df2 (ID as index, Count as value)
df2_count_lookup = df2.set_index('ID')['Count']

# Fill NA values in df1's Count column with matching values from df2
df1['Count'] = df1['Count'].fillna(df1['ID'].map(df2_count_lookup))

# df1 now matches your target df3
print(df1)

How this works:

  • df2.set_index('ID')['Count'] converts df2 into a Series where each ID acts as an index, making it easy to look up corresponding Count values.
  • df1['ID'].map(df2_count_lookup) matches every ID in df1 to its associated Count value from df2.
  • fillna() only replaces the NA values in df1's Count column with these matched values—all existing non-NA values stay exactly as they are.

Solution 2: Use combine_first()

This method uses pandas' built-in function to merge and fill missing values in one streamlined step.

# Align both DataFrames by setting ID as the index
df1_indexed = df1.set_index('ID')
df2_indexed = df2.set_index('ID')

# Combine data: keep df1's values where available, fill NA with df2's values
df3 = df1_indexed.combine_first(df2_indexed).reset_index()

print(df3)

How this works:

  • set_index('ID') ensures both DataFrames are aligned by their ID values, so matching rows line up perfectly.
  • combine_first() prioritizes df1's data, only filling in missing (NA) values with the corresponding data from df2.
  • reset_index() converts the ID index back to a regular column, matching the structure of your target df3.

Both solutions will output exactly the df3 you're looking for:

ID  Count
0  11  345.0
1  22  456.0
2  33  786.0
3  44  765.0
4  55  890.0
5  66  888.0
6  77  654.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:34:40