Skip to main content
 首页 » 编程设计

python之关于 numpy 沿轴应用和列表理解的困惑

2025年05月04日13落叶

好吧,如果我只是问一些愚蠢的问题,我提前道歉,但我真的以为我理解了 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 是纯 Python,您可以自行查看和解码。在这种情况下,它本质上是:

check = np.empty(child_array.shape,dtype=object) 
for i in range(child_array.shape[1]): 
    check[:,i] = Leaf(child_array[:,i]) 

换句话说,它预先分配容器数组,然后通过迭代填充值。这当然比追加到数组要好,但很少比将值追加到列表好(这是理解所做的)。

您可以采用上述模板并对其进行调整以生成您真正想要的数组。

for i in range(check.shape[0]): 
    check[i]=Leaf(child_array[i,:]) 

在快速测试中,此迭代次数与理解次数相同。 apply_along_axis 除了错误之外,还比较慢。