类子集的键入提示

问题描述 投票:0回答:1

我正在编写使用

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
的子类)?

python type-hinting
1个回答
0
投票

您可以显式执行

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]
© www.soinside.com 2019 - 2024. All rights reserved.