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

服务器容量统计Python脚本运行报TypeError: float与str无法比较求助

问题根源

错误发生在max_value = column.max()这行,是因为Report Timestamp Number列同时存在字符串类型的时间戳和float类型的空值(NaN),pandas求最大值时需要逐行比较值的大小,字符串和float不支持比较运算,因此触发报错。

排查步骤
  • 先确认列的类型分布,执行以下代码查看该列的类型统计:
print(Main_Table["Report Timestamp Number"].apply(type).value_counts())

正常应该会同时输出<class 'str'>和<class 'float'>两类结果,证明列内数据类型不统一。

  • 查看异常的float类型值,确认是不是空值:
print(Main_Table[Main_Table["Report Timestamp Number"].apply(lambda x: isinstance(x, float))]["Report Timestamp Number"])

输出结果基本都是NaN,这些空值来自多表左连接时匹配失败的行。

解决方案

方案1 修复当前列的类型问题

把时间戳列统一转为数值类型,过滤空值后再求最大值:

# 将字符串时间戳转成整数,无法转换的空值会自动处理为缺失值
Main_Table['Report Timestamp Number'] = pd.to_numeric(Main_Table['Report Timestamp'], errors='coerce')
# 过滤空值后求最大值
max_value = Main_Table["Report Timestamp Number"].dropna().max()

方案2 更稳妥的优化(推荐)

不要把datetime转成字符串再比较大小,直接使用原始datetime类型的Report Timestamp列计算最大值,完全避免类型冲突:

# 直接用原始datetime列求最大值,不用转字符串的列运算
max_value = Main_Table['Report Timestamp'].max()

# 后续的判断逻辑也对应修改,使用原始datetime列判断
def f(row):
    global Total_Memory_Latest
    if row['Report Timestamp'] == max_value and row['Host/GuestVM'] == 'Host':
        Total_Memory_Latest += row['Total Physical Memory GB']
        return 0
    else:
        return np.nan

额外潜在问题修复

你当前存储计算的函数注释了try-except,若Capacity(TB)列存在非数字字符串,float(df['Capacity(TB)'])也会触发报错,建议改为以下写法:

def f(row):
    try:
        capacity = pd.to_numeric(row['Capacity(TB)'], errors='coerce')
        if pd.notna(capacity) and capacity >= 0.01:
            available = pd.to_numeric(row['Available(TB)'], errors='coerce')
            if pd.notna(available):
                return round((available/capacity)*100)
        return ''
    except:
        return np.nan

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:36:03