子类化 ndarray 在 pySpark 中广播时会丢弃信息



我希望有人可以帮助我调试我们在 Spark 中看到的子类化ndarray的问题。特别是当广播子类数组时,它似乎丢失了额外的信息。下面是一个简单的例子:

>>> import numpy as np
>>> 
>>> class Test(np.ndarray):
...     def __new__(cls, input_array, info=None):
...         obj = np.asarray(input_array).view(cls)
...         obj.info = info
...         return obj
...     
...     def __array_finalize__(self, obj):
...         if not hasattr(self, "info"):
...             self.info = getattr(obj, 'info', None)
...         else:
...             print("has info attribute: %s" % getattr(self, 'info'))
... 
>>> test = Test(np.array([[1,2,3],[4,5,6]]), info="info")
>>> print(test.info)
info
>>> print(sc.broadcast(test).value)
[[1 2 3]
 [4 5 6]]
>>> print(sc.broadcast(test).value.info)
None

至少,您有一个小错别字 - 您正在检查hasattr(obj, "info")而不是您应该检查if hasattr(self, "info")。 由于 if 语句翻转,信息不会被转移。

test = Test(np.array([[1,2,3],[4,5,6]]), info="info")
print test.info # info
test2 = test[1:]
print test2.info # info

最新更新