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

Python中DataFrame多列缺失值处理:指定列与众数填充结合

批量填充DataFrame缺失值:指定值+列众数

完整实现代码

import pandas as pd
import numpy as np

# 构造示例数据
data = {'a':  [1,1,0,1,1],
        'b': ['a', 'b', np.nan, 'c', np.nan],
        'c': ['b1','b2',np.nan, 'c1', np.nan],
        'd': [1,1,1, 2, np.nan],
        'e': [4,4,4, 3, np.nan]
       }
df = pd.DataFrame(data)

# 1. 用指定值填充a、b、c列的缺失值
fill_specified = {'a':0, 'b':'other', 'c':-1}
df = df.fillna(fill_specified)

# 2. 对剩余列用列众数填充缺失值
other_cols = df.columns.difference(['a', 'b', 'c'])
# 计算每列众数,取第一个众数(处理多众数场景)
mode_values = df[other_cols].mode().iloc[0]
# 批量填充
df = df.fillna(mode_values)

print(df)

运行结果

a      b   c    d    e
0  1      a  b1  1.0  4.0
1  1      b  b2  1.0  4.0
2  0  other  -1  1.0  4.0
3  1      c  c1  2.0  3.0
4  1  other  -1  1.0  4.0

步骤说明

  • 指定值填充目标列:通过fillna()传入字典,精准匹配a、b、c列的缺失值填充规则,和你原有的实现逻辑一致。
  • 筛选剩余列并计算众数:用columns.difference()快速获取除a、b、c外的所有列;mode()计算每列众数,由于部分列可能存在多个众数,用iloc[0]取第一个出现的众数作为填充值。
  • 批量众数填充:再次调用fillna(),传入众数字典,自动匹配列名完成剩余列的缺失值填充,无需逐个列手动设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:35:18