我正在编写使用
pandas.Series
作用于 DatetimeIndex
的函数。我可以进行键入提示,如下所示:
import pandas as pd
def filter_year(s: pd.Series, year: int) -> pd.Series:
keep = s.index.year == year
return s[keep]
这工作正常,但编辑抱怨
Cannot access attribute "year" for class "Index"
。原因是,编辑期望any Index
。
有没有办法指定
s
有一个DatetimeIndex
(它是Index
的子类)?
您可以显式执行
cast
来表示 s.index
属于 DatetimeIndex
类型。
import pandas as pd
from typing import cast
from pandas import DatetimeIndex
def filter_year(s: pd.Series, year: int) -> pd.Series:
s.index = cast(DatetimeIndex, s.index)
keep = s.index.year == year
return s[keep]