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

Python2.7:np.where生成np.nan无效,fillna无法替换及列合并问题求助

解决Python 2.7中Pandas列合并与缺失值识别问题

首先咱们拆解你遇到的两个核心问题:为什么np.nan没被识别为缺失值,以及如何正确合并这三列。

问题根源:字符串与np.nan的类型冲突

你用np.where生成列时,条件满足时返回字符串(比如"clear"),不满足时返回np.nan(浮点类型)。np.where会自动统一返回数组的类型,这里会把np.nan转换成字符串形式的'nan',而不是Pandas能识别的真正缺失值。这就是为什么df.isnull().sum()显示没有空值——这些'nan'是普通字符串,不是缺失标记!

修复方案

第一步:生成真正带缺失值的列

去掉多余的str(),同时确保Pandas能识别缺失值。更稳妥的方式是直接用pd.np.nan(适配Python2.7的老版本Pandas):

df['clear lap?'] = np.where(df['position'] == df['position'].shift(), "clear", pd.np.nan)
df['overtaken'] = np.where(df['position'] > df['position'].shift(), "got overtaken", pd.np.nan)
df['overtook'] = np.where(df['position'] < df['position'].shift(), "overtook", pd.np.nan)

现在再运行df.isnull().sum(),就能看到对应的缺失值计数了。

第二步:合并三列成目标列

不需要多次调用fillna,链式调用就能一步到位:

df['lap_status'] = df['clear lap?'].fillna(df['overtaken']).fillna(df['overtook'])

或者用combine_first实现同样效果:

df['lap_status'] = df['clear lap?'].combine_first(df['overtaken']).combine_first(df['overtook'])

更高效的替代方案:直接生成目标列

其实你不需要先创建三个中间列,用np.select可以一次性生成最终结果,代码更简洁性能也更好:

conditions = [
    df['position'] == df['position'].shift(),
    df['position'] > df['position'].shift(),
    df['position'] < df['position'].shift()
]
choices = [
    "clear",
    "got overtaken",
    "overtook"
]

df['lap_status'] = np.select(conditions, choices, default=np.nan)

这个方法直接根据三个条件生成对应值,不满足任何条件时返回真正的np.nan,完美匹配你的需求。

验证结果

运行完上述代码后,你可以用df['lap_status'].isnull().sum()检查缺失值,同时查看列内容确认合并是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:05:39