Python3 default关键字作为type的默认值?

2024-06-28 19:13:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

default(int)0

default(decimal)0.0

default(MyCustomClassType)null

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

任何提示都将不胜感激。非常感谢。你知道吗


Tags: 数据函数default类型pandasnet整数nan
1条回答
网友
1楼 · 发布于 2024-06-28 19:13:02

如注释中所述,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>

相关问题 更多 >