Pandas如何在for循环中关联其他列为指定列填充NaN值
问题解决说明及代码
你原代码的问题如下:
- 切片
df.iloc[:,0:1]为左闭右开规则,仅选中第0列,无法覆盖animal1、animal2两个目标列 - 循环中取到的
column是列名字符串,直接调用fillna不会修改原DataFrame,且没有正确匹配偏移+2的填充列 - fillna方法默认返回新对象,需要赋值回原列或者指定
inplace=True才会生效
循环实现方案(适配多列扩展需求)
通过列索引偏移匹配目标列和填充列,完全符合你要求的遍历逻辑:
import pandas as pd import numpy as np # 构造示例DataFrame df = pd.DataFrame([[np.nan,"cat","mouse", 'tiger'], ["tiger","dog","elephant", "mouse"], ["cat",np.nan,"giraffe", "cat"], [np.nan,np.nan,"ant", "ant"]], columns=["animal1","animal2","animal3", "animal4"]) # 遍历前2列,用索引+2的对应列填充空值 for col_idx in range(2): df.iloc[:, col_idx] = df.iloc[:, col_idx].fillna(df.iloc[:, col_idx+2]) print(df)
运行结果
animal1 animal2 animal3 animal4 0 mouse cat mouse tiger 1 tiger dog elephant mouse 2 cat cat giraffe cat 3 ant ant ant ant
更稳妥的列名匹配方案
如果担心后续列顺序变动导致偏移不准,可以用列名映射的方式实现,逻辑完全一致:
col_map = { "animal1": "animal3", "animal2": "animal4" } for target_col, fill_col in col_map.items(): df[target_col] = df[target_col].fillna(df[fill_col])
内容的提问来源于stack exchange,提问作者Jameson
相关产品推荐
相关产品推荐

