Qas*_*wed 6 python series type-hinting pandas
My function returns a pandas series, where all elements have a specific type (say str). The following MWE should give an impression:
import pandas as pd
def f() -> pd.Series:
return pd.Series(['a', 'b'])
Run Code Online (Sandbox Code Playgroud)
Within the type hints I want to make clear, that f()[0] will always be of type str (compared for example to a function that would return pd.Series([0, 1])). My initial guess was to use def f() -> pd.Series[str]: what gives the TypeError: 'type' object is not subscriptable.
So, how to specify the type of pandas series elements in type hints?
Pet*_*ott 11
您可以用于pandera类型提示和验证数据帧和系列:https://pandera.readthedocs.io/en/stable/schema_models.html#schema-models
所以在这种情况下:
from pandera.typing import Series
import pandas as pd
def f() -> Series[str]:
return pd.Series(['a', 'b'])
Run Code Online (Sandbox Code Playgroud)
小智 10
对于 python 3.8 尝试:
def f() -> "pd.Series[str]":
pass
Run Code Online (Sandbox Code Playgroud)
或者:
f_return_type = "pd.Series[str]"
def f() -> f_return_type:
pass
Run Code Online (Sandbox Code Playgroud)
或# type: pd.Series[str]对于变量