升级Python3.11后pandas sum行为变更,如何恢复旧逻辑?
Python3.11升级后Pandas sum返回None而非NaN的问题解决
问题场景
将Python从3.9升级到3.11后,运行原有Pandas代码时出现异常:当Bresser_sum和open gauge_sum列均为NaN时,sum(axis=1, min_count=1)计算出的br_open_sum列返回None而非之前的NaN值。尝试调整skipna、numeric_only、min_count等参数组合无效,使用fillna()处理None时也报错。
原代码
opendf = pd.DataFrame( rdbin[0], columns=[ "highpoint_sum", "highpoint_mean", "highpoint diff_sum", "highpoint diff_mean", "name", "bin", ], ) opendf.index = opendf["bin"] opendf.drop( columns=["highpoint_sum", "highpoint_mean", "highpoint diff_mean", "name", "bin"], inplace=True, ) opendf["Bresser_sum"] = brbinarr[:, 2] opendf["open gauge_sum"] = rdbin[21][:, 2] opendf["br_open_sum"] = opendf[["Bresser_sum", "open gauge_sum"]].sum( axis=1, min_count=1 )
异常输出示例
highpoint diff_sum Bresser_sum open gauge_sum br_open_sum bin 2021-07-19 00:00:00 0.0 NaN NaN None 2021-07-19 01:00:00 0.0 NaN NaN None 2021-07-19 11:00:00 0.0 0 NaN 0 2021-07-19 12:00:00 0.0 0.0 NaN 0.0
解决方法
1. 统一列的数值类型(核心解决步骤)
问题根源是Bresser_sum或open gauge_sum列因混入None变成了object类型,而非数值类型,导致sum计算返回None,且fillna()无法直接处理。先将列转为数值类型,自动把None转为NaN:
import pandas as pd import numpy as np # 转换列为数值类型,非数值值转为NaN opendf["Bresser_sum"] = pd.to_numeric(opendf["Bresser_sum"], errors='coerce') opendf["open gauge_sum"] = pd.to_numeric(opendf["open gauge_sum"], errors='coerce')
2. 重新计算或修复已生成的br_open_sum
- 若还未计算
br_open_sum,重新运行sum代码即可得到NaN而非None:opendf["br_open_sum"] = opendf[["Bresser_sum", "open gauge_sum"]].sum(axis=1, min_count=1) - 若已生成含None的
br_open_sum,直接将None转为NaN:opendf["br_open_sum"] = pd.to_numeric(opendf["br_open_sum"], errors='coerce')
3. 处理原始数组(从源头避免None)
如果brbinarr或rdbin数组本身包含None而非NaN,提前将数组中的None替换为NaN,再赋值给DataFrame:
# 假设是numpy数组,替换None为NaN brbinarr = np.where(brbinarr == None, np.nan, brbinarr) rdbin[21] = np.where(rdbin[21] == None, np.nan, rdbin[21])
4. 使用fillna()处理NaN
完成类型转换后,即可正常使用fillna()替换NaN为需要的值:
# 将NaN替换为0,根据需求调整值 opendf["br_open_sum"].fillna(0, inplace=True)
内容的提问来源于stack exchange,提问作者matt cooper
相关产品推荐
相关产品推荐

