以下代码在 vs code 中不断返回 AttributeError,但在 Google Colab 上运行相同的代码时,不会产生此类错误:
代码:
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'
我的理解是,由于我调用 season() 函数作为链式 groupby 函数的参数,where() 函数应该能够从雪对象获取年份。但不知怎的,这并没有发生。
为了确保我的代码中没有语法错误,在 Google Colab 上运行了这段代码,我没有遇到任何此类问题。我附上了 Google Colab 输出的屏幕截图供您细读:
我还浏览了该平台上 AttributeError 的所有可用解决方案,但找不到任何解决方案,该错误仅限于 VS Code 而不是 Google Colab 或 Juputer Notebook 终端。
当 groupby 接受一个函数时,它会在每个值上调用它,这不是向量化的。
by:映射、函数、标签、pd.Grouper 或此类列表
用于确定groupby的组。 如果 by 是一个函数,则会在对象索引的每个值上调用它。如果一个字典或系列 通过后,Series 或 dict VALUES 将用于确定 组(系列的值首先对齐;请参阅 .align() 方法)。如果 传递长度等于所选轴的列表或 ndarray(请参阅 groupby 用户指南),这些值按原样使用来确定 组。标签或标签列表可以通过 self 中的列。请注意,元组被解释为(单个)键。
您可以使用:
snow.groupby(season(snow.index)).sum()