gpt4 book ai didi

Python3 - 类型默认值的默认关键字?

转载 作者:行者123 更新时间:2023-12-01 04:04:52 24 4
gpt4 key购买 nike

Python3 有类似 default keyword 的东西吗?来自.NET?也就是说,给定一个类型,它会生成该类型的一个值,该值通常称为该类型的默认值。例如:

默认(int)0

默认(十进制)0.0

default(MyCustomClassType)null

我希望这样的事情已经存在,因为我想预处理 pandas 数据帧中的值,并将整数列等的 NaN 替换为 0,并避免编写自己的函数(每个函数都包含一个巨大的开关)可能的类型,以模仿我之前举例的行为(来自 .NET)。

任何指点将不胜感激。谢谢。

最佳答案

如注释中所述,Python 类型如 intfloatstrlist 等。都是可调用的,即您可以使用 int() 并获取 0,或 str()list() > 并获取一个空字符串或列表。

>>> type(42)()
0

同样的情况也适用于 numpy 类型。您可以使用 dtype 属性获取 numpy 数组的类型,然后使用它来初始化“缺失”值:

>>> A = np.array([1, 2, 3, 4, float("nan")]) # common type is float64
>>> A
array([ 1., 2., 3., 4., nan])
>>> A[np.isnan(A)] = A.dtype.type() # nan is replaced with 0.0
>>> A
array([ 1., 2., 3., 4., 0.])
>>> B = np.array([1, 2, 3, -1, 5]) # common type is int64
>>> B
array([ 1, 2, 3, -1, 5])
>>> B[B == -1] = B.dtype.type() # -1 is replaced with
>>> B
array([1, 2, 3, 0, 5])

这也适用于提供无参数构造函数的其他类,但是,结果将是该类的实例,而不是示例中的 null ..

>>> class Foo(object): pass
>>> type(Foo())()
<__main__.Foo at 0x7f8b124c00d0>

关于Python3 - 类型默认值的默认关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com