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

仅填充双列含NaN的指定行数据:需求与实现示例

问题说明

我们需要处理一份包含缺失值的表格数据,要求**仅对day和month列同时为NaN的行(索引3)**填充指定值:day=1、month=01,其余含NaN的行保持原有缺失状态。

原始数据如下:

indexdaymonthyear
0NaN0393
118NaN85
28771
3NaNNaN75
解决方案

思路

核心是精准定位符合条件的行:通过逻辑与(&)筛选出day和month均为缺失值的行,然后对这部分行的指定列进行填充,其他行不受影响。

代码实现(以Pandas为例)

import pandas as pd
import numpy as np

# 构造原始数据集
df = pd.DataFrame(
    data={
        'day': [np.nan, 18, 8, np.nan],
        'month': ['03', np.nan, 7, np.nan],
        'year': [93, 85, 71, 75]
    },
    index=[0, 1, 2, 3]
)

# 定位并填充目标行
df.loc[(df['day'].isna()) & (df['month'].isna()), ['day', 'month']] = [1, '01']

# 输出处理后的数据
print(df)

处理结果

执行代码后,得到的数据集如下:

indexdaymonthyear
0NaN0393
118NaN85
28771
310175

这样就完美实现了需求:只有索引3的行被填充,其他含NaN的行保持原样。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:42:45