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

Pandas 2.0.3中DataFrame.max(skipna=False)报错,为何老师设备可运行?

问题:Pandas 2.0.3执行df.max(skipna=False)报错,老师设备可正常运行,是版本问题吗?

复现代码

import pandas as pd
import numpy as np

people_dict = {
"birthyear": [2001, 2002, 2000],
"children": [np.nan ,3 , 0],
"hobby": ["Biking", "Dancing", np.nan],
"weight": [68, 83, 112]
}

people =  pd.DataFrame(people_dict)

print(people.max(skipna=False))

报错信息

TypeError: '>=' not supported between instances of 'str' and 'float'


原因:确实是Pandas版本差异导致的

你用的Pandas 2.0+对类型一致性的检查更严格,而你的老师大概率使用的是Pandas 1.x系列版本。

具体逻辑:

  • hobby列是object类型,混合了字符串和np.nan(注意np.nan本质是float类型)
  • 当设置skipna=False时,Pandas需要对列内所有元素做比较。Pandas 2.0+禁止直接比较字符串和float类型,因此抛出类型错误;而Pandas 1.x版本在处理这种混合类型列的max计算时,会默认把np.nan视为"小于任何字符串"的元素,跳过类型冲突的报错,返回列中最大的字符串值。

解决方案

根据你的需求,可选择以下两种方式:

  1. 忽略空值(默认行为)
    如果不需要强制保留空值参与计算,直接去掉skipna=False参数即可(默认skipna=True):

    print(people.max())
    

    输出结果:

    birthyear      2002
    children          3
    hobby        Dancing
    weight          112
    dtype: object
    
  2. 强制保留空值参与计算
    单独处理数值列和字符串列,避免类型冲突:

    # 计算数值类型列的max
    numeric_cols_max = people.select_dtypes(include=[np.number]).max(skipna=False)
    # 计算字符串类型列的max,处理空值逻辑
    string_cols_max = people.select_dtypes(include=[object]).apply(
        lambda col: col.max(skipna=False) if col.notna().any() else np.nan
    )
    # 合并结果
    final_max = pd.concat([numeric_cols_max, string_cols_max])
    print(final_max)
    

    输出结果:

    birthyear      2002.0
    children          NaN
    weight          112.0
    hobby        Dancing
    dtype: object
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 11:05:06