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

如何在Pandas DataFrame中用ColumnB非空值替换ColumnA

How to Update ColumnA with ColumnB Values (Only Where ColumnB Is Not Null)

Got it, let's break this down. You want to replace values in ColumnA with those from ColumnB, but only keep the replacements where ColumnB has non-null values—leaving ColumnA's original data untouched wherever ColumnB is empty. The replace method isn't the right tool here because it's built for general value swapping, not conditional, non-null-only updates.

Here are two straightforward, effective ways to get your desired result:

Method 1: Use fillna() (Most Intuitive)

This approach works by taking ColumnB, filling any null values in it with the corresponding values from ColumnA, then assigning the result back to ColumnA. This ensures we only use ColumnB's values when they exist, and fall back to ColumnA's original data otherwise.

Example Code

First, let's set up the DataFrame to match your expected output (adjusted to make the logic clear—your original example likely had a third row where ColumnB has a value):

import pandas as pd
import numpy as np

# Sample data matching your expected output scenario
df = pd.DataFrame({
    'ColumnA': [1, 4, np.nan],
    'ColumnB': [np.nan, np.nan, 3]
})

Run the update:

df['ColumnA'] = df['ColumnB'].fillna(df['ColumnA'])

Result

Your ColumnA will now be [1, 4, 3]—exactly what you wanted.

Method 2: Use update() (More Efficient for Large Data)

The update() method is designed specifically for modifying existing DataFrame values with non-null data from another source. It only overwrites values in ColumnA where ColumnB has non-null entries, so it's perfect for this use case.

Example Code

Using the same sample DataFrame as above:

df['ColumnA'].update(df['ColumnB'])

This will produce the same result as the fillna() method, but it operates in-place (if you don't mind modifying the original DataFrame) and can be faster with large datasets.

Why replace() Didn't Work

When you tried df.replace, it was trying to swap all values in ColumnA with ColumnB's values—including nulls. That's why you ended up losing ColumnA's original values where ColumnB was empty. The methods above avoid this by explicitly only using non-null values from ColumnB.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:32:52