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

Python Dataframe条件填充:指定列匹配且空值时替换内容

解决Pandas按条件替换空值的问题

首先,你的原始DataFrame创建代码如下:

import pandas as pd
df = pd.DataFrame({'Type':["A","B","A", "C", "A"],'Value':["sesame", None, None, "tea", "bun"]})

你之前尝试的df.loc[df['Type'] == 'A', ['Value']].fillna(value='custard', axis=1)之所以无效,是因为这种写法返回的是原DataFrame的切片副本,默认不会修改原数据。要实现按条件替换空值,可以用以下两种可靠方法:

方法一:直接用loc定位赋值

这种方式直观,适合条件较少的场景:

# 替换Type为"A"且Value为空的值
df.loc[(df['Type'] == 'A') & df['Value'].isna(), 'Value'] = 'custard'
# 替换Type为"B"且Value为空的值
df.loc[(df['Type'] == 'B') & df['Value'].isna(), 'Value'] = 'peanuts'

执行后,输出的DataFrame符合预期:

Type    Value
0    A   sesame
1    B   peanuts
2    A  custard
3    C      tea
4    A      bun

方法二:用np.select处理多条件

如果后续有更多条件需要扩展,推荐使用numpy.select,代码结构更清晰:

import numpy as np

# 定义条件列表和对应的替换值
conditions = [
    (df['Type'] == 'A') & df['Value'].isna(),
    (df['Type'] == 'B') & df['Value'].isna()
]
choices = ['custard', 'peanuts']

# 应用替换,默认保留原Value值
df['Value'] = np.select(conditions, choices, default=df['Value'])

两种方法都能实现你的需求,可根据实际条件数量选择合适的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:06:06