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

技术求助:如何将Pandas DataFrame中的空白值替换为"0"?

解决DataFrame空白值替换为"0"的问题

嗨,我来帮你搞定这个DataFrame的空白值替换需求!根据你提供的原始数据和预期结果,我们可以用pandas的fillna()方法轻松实现,下面是具体步骤和代码示例:

原始数据整理

先把你给出的原始数据整理成清晰的表格形式:

YearDividendsVolumeCloseCompanySector
20090.280000(空白)10.35ABCFinance
20100.2800005.264694e+069.88ABCFinance
20110.5600005.153132e+068.26ABCFinance
20120.5600003.930295e+06(空白)ABCFinance
2013(空白)4.085875e+0613.16ABCFinance

解决方案

在pandas中,这类空白值通常会被识别为NaN,我们可以用fillna()方法批量替换成"0",分两种场景处理:

场景1:统一替换为字符串"0"

如果你不介意数值列变成字符串类型,直接一行代码就能搞定:

import pandas as pd

# 模拟你的DataFrame数据
df = pd.DataFrame({
    'Year': [2009, 2010, 2011, 2012, 2013],
    'Dividends': [0.28, 0.28, 0.56, 0.56, None],
    'Volume': [None, 5.264694e+06, 5.153132e+06, 3.930295e+06, 4.085875e+06],
    'Close': [10.35, 9.88, 8.26, None, 13.16],
    'Company': ['ABC']*5,
    'Sector': ['Finance']*5
})

# 替换所有NaN值为"0"
df = df.fillna('0')

# 查看最终结果
print(df)

执行后就能得到你预期的效果,所有空白位置都被替换成"0"。

场景2:数值列替换为数值0,非数值列替换为字符串"0"

如果你希望数值列保持数值类型(方便后续做计算),可以区分列类型分别处理:

import pandas as pd

# 模拟你的DataFrame数据
df = pd.DataFrame({
    'Year': [2009, 2010, 2011, 2012, 2013],
    'Dividends': [0.28, 0.28, 0.56, 0.56, None],
    'Volume': [None, 5.264694e+06, 5.153132e+06, 3.930295e+06, 4.085875e+06],
    'Close': [10.35, 9.88, 8.26, None, 13.16],
    'Company': ['ABC']*5,
    'Sector': ['Finance']*5
})

# 筛选出数值类型的列
numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
# 筛选出非数值类型的列
non_numeric_cols = df.select_dtypes(exclude=['int64', 'float64']).columns

# 数值列填充数值0,非数值列填充字符串"0"
df[numeric_cols] = df[numeric_cols].fillna(0)
df[non_numeric_cols] = df[non_numeric_cols].fillna('0')

# 查看最终结果
print(df)

这样处理后,Dividends、Volume、Close这些数值列里的空白会被替换成数值0,非数值列的空白则替换成字符串"0",更适合后续的数据运算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:18:15