pandas.api.extensions.ExtensionDtype.construct_from_string#
- classmethod ExtensionDtype.construct_from_string(string)[源代码]#
从字符串构造此类型。
这主要适用于接受参数的数据类型。例如,周期dtype接受的频率参数可以设置为
period[H]
(其中H表示每小时班次)。默认情况下,在抽象类中,只需要类型的名称。但子类可以重写此方法以接受参数。
- 参数
- string应力
类型的名称,例如
category
。
- 退货
- ExtensionDtype
数据类型的实例。
- 加薪
- TypeError
如果不能从这个“字符串”构造一个类。
示例
对于带有参数的扩展数据类型,以下可能是一种适当的实现。
>>> @classmethod ... def construct_from_string(cls, string): ... pattern = re.compile(r"^my_type\[(?P<arg_name>.+)\]$") ... match = pattern.match(string) ... if match: ... return cls(**match.groupdict()) ... else: ... raise TypeError( ... f"Cannot construct a '{cls.__name__}' from '{string}'" ... )