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

Python中基于指定条件合并同结构DataFrame:保留原结构替换指定单元格值

Replace "x" Values in a DataFrame with Corresponding Values from Another Identical DataFrame

Got it, this is a common conditional replacement task that pandas handles smoothly with its built-in methods. Let's walk through how to achieve exactly what you need—keeping df_a's structure intact, only swapping out cells with "x" for the matching values from df_b.

Step 1: Recreate the Example DataFrames

First, let's build the df_a and df_b from your example to work with:

import pandas as pd
import numpy as np

# Construct df_a as per your data
df_a = pd.DataFrame({
    "2022": ["x", np.nan, np.nan],
    "2023": ["x", np.nan, "x"],
    "2024": ["x", "x", "x"],
    "2025": [np.nan, "x", "x"],
    "2026": [np.nan, np.nan, "x"],
    "2027": [np.nan, np.nan, "x"]
})

# Construct df_b as per your data
df_b = pd.DataFrame({
    "2022": [4, 5, 6],
    "2023": [7, 8, 9],
    "2024": [8, np.nan, 4],
    "2025": [np.nan, np.nan, 3],
    "2026": [np.nan, np.nan, 2],
    "2027": [np.nan, np.nan, np.nan]
})

Step 2: Perform the Conditional Replacement

You have two straightforward options using pandas' mask() or where() methods—both will give you the desired result:

Option 1: Use mask()

The mask() method replaces values where the condition is True (in this case, where df_a has "x") with the corresponding values from df_b:

df_final = df_a.mask(df_a == "x", df_b)

Option 2: Use where()

The where() method does the opposite—it keeps values where the condition is True, and replaces others. Here, we use it to keep df_b's values where df_a is "x", otherwise retain df_a's values:

df_final = df_b.where(df_a == "x", df_a)

Step 3: Verify the Result

If you print df_final, you'll get exactly the output you expected:

2022  2023  2024  2025  2026  2027
0   4.0   7.0   8.0   NaN   NaN   NaN
1   NaN   NaN   5.0   8.0   NaN   NaN
2   NaN   6.0   9.0   4.0   3.0   2.0

Optional: Standardize Data Types

Since df_a initially has string values ("x") and NaNs, the resulting df_final might have mixed types. To convert all columns to numeric (while keeping NaNs as-is), you can run:

df_final = df_final.apply(pd.to_numeric, errors="ignore")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:17:46