如何在类型提示中指定 pandas 系列元素的类型? [英] How to specify the type of pandas series elements in type hints?

查看:67
本文介绍了如何在类型提示中指定 pandas 系列元素的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的函数返回一个熊猫系列,其中所有元素都具有特定类型(例如str).以下MWE应该会给人留下印象:

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']) 

在我要说明的类型提示中,f()[0]始终为str类型(例如,与返回pd.Series([0, 1])的函数相比).我最初的猜测是使用def f() -> pd.Series[str]:给出TypeError: 'type' object is not subscriptable的原因.

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?

推荐答案

不幸的是,Python的类型提示不支持此功能.尽管如此,您始终可以使用dataenforce库(链接)来添加提示甚至执行验证

Unfortunately Python's type hinting does not support this out of the shelf. Nonetheless, you can always make use of dataenforce library (link) to add hints or even enforce validation.

这篇关于如何在类型提示中指定 pandas 系列元素的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆