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

VS Code报AttributeError:int无where属性,同代码Google Colab运行正常

问题:同一代码在VS Code报错AttributeError但Colab正常运行

下面这段代码在Google Colab中可正常执行,但在VS Code运行时持续抛出AttributeError:

import numpy as np
import pandas as pd

url = 'https://github.com//mattharrison/datasets/raw/master/data/alta-noaa-1980-2019.csv'

alta_df = pd.read_csv(url)

dates = pd.to_datetime(alta_df.DATE)

snow = alta_df.SNOW.rename(dates)

def season(idx):
    year = idx.year
    month = idx.month
    return year.where((month<10), year+1)

snow.groupby(season).sum()

错误信息:

AttributeError                            Traceback (most recent call last)
File

    388 year = idx.year
    389 month = idx.month
--> 390 return year.where((month<10), year+1)

AttributeError: 'int' object has no attribute 'where'

问题原因

核心差异来自Pandas版本:

  • Colab使用的是较新版本Pandas,groupby传递自定义函数时,会把整个索引序列传给函数,此时idx是DatetimeIndex,idx.year返回的是Pandas整数序列,具备where方法,因此代码正常运行。
  • VS Code环境的Pandas版本偏旧,groupby会逐个传递索引元素,此时idx是单个Timestamp对象,idx.year返回普通整数,整数没有where方法,因此触发报错。

解决方案

方案一:兼容两种参数传递逻辑

修改season函数,判断输入是单个时间戳还是序列,分别处理:

def season(idx):
    if isinstance(idx, pd.Timestamp):
        year = idx.year
        month = idx.month
        return year if month < 10 else year + 1
    year = idx.year
    month = idx.month
    return year.where((month < 10), year + 1)

方案二:改用向量化方式生成分组键(推荐)

避开自定义函数的版本差异,直接基于索引生成分组键后再分组:

import numpy as np
import pandas as pd

url = 'https://github.com//mattharrison/datasets/raw/master/data/alta-noaa-1980-2019.csv'

alta_df = pd.read_csv(url)
dates = pd.to_datetime(alta_df.DATE)
snow = alta_df.SNOW.rename(dates)

# 直接生成分组键
season_key = snow.index.year.where(snow.index.month < 10, snow.index.year + 1)
# 分组求和
result = snow.groupby(season_key).sum()
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 11:17:43