【发布时间】:2014-12-25 05:59:40
【问题描述】:
好的,所以如果我只是问一些愚蠢的问题,我提前道歉,但我真的认为我理解 apply_along_axis 的工作原理。我刚刚遇到了一些可能是我没有考虑过的边缘情况,但这让我感到困惑。简而言之,这是让我感到困惑的代码:
class Leaf(object):
def __init__(self, location):
self.location = location
def __len__(self):
return self.location.shape[0]
def bulk_leaves(child_array, axis=0):
test = np.array([Leaf(location) for location in child_array]) # This is what I want
check = np.apply_along_axis(Leaf, 0, child_array) # This returns an array of individual leafs with the same shape as child_array
return test, check
if __name__ == "__main__":
test, check = bulk_leaves(np.random.ran(100, 50))
test == check # False
我总是觉得在 numpy 中使用列表推导然后再转换回数组很愚蠢,但我不确定另一种方法可以做到这一点。我只是错过了一些明显的东西吗?
【问题讨论】:
-
apply_along_axis从不修改其输入。它返回一个新数组。 -
措辞错误,我的意思是 check 与 child_array 的形状相同
-
什么是
child_array? -
Leaf实例的数组将具有 dtypeobject。这些数组的内存效率并不比普通的 Python 列表高,执行任何计算的速度也不比使用普通 Python 列表的等效代码快(考虑到创建数组的成本,它通常更慢)。它提供的只是ndarray 索引syntax。你确定要使用 NumPy 数组吗? -
@BrenBarn 只是一个随机数数组。一个
np.random.rand(x, y)
标签: python object numpy vectorization