【问题标题】:Stacking and adding up numpy arrays堆叠和累加 numpy 数组
【发布时间】:2014-06-20 00:21:53
【问题描述】:

我有一个数组g

g = np.array([])

我有一些循环,我需要在 python 中使用以下结构构建它:

[
[1 4 
 2 5 
 3 6]
[7 10
 8 11
 9 12]
]
...

即任意数量的行(假设为 10),但每个条目由一个 3x2 数组组成。

在顶部初始化g后,我正在这样做:

       curr_g = np.array([])
       for y, w in zip(z.T, weights.T):
            temp_g = sm.WLS(y, X, w).fit()
            # temp_g.params produces a (3L,) array
            # curr_g is where I plan to end up with a 3x2 array
            curr_g = np.hstack((temp_g.params, curr_g))

        g = np.hstack((temp_g.params, g))

我认为当我将hstack 与两个 3x1 数组一起使用时,我最终会得到一个 3x2 数组。但发生的情况是,在堆叠之后,curr_g 只是从 (3L,) 变为 (6L,)...

另外,一旦我有一个 3x2 数组,我如何将 3x2 数组堆叠在一起?

【问题讨论】:

    标签: python arrays numpy stack


    【解决方案1】:

    你说得对,“当我将 hstack 与两个 3x1 数组一起使用时,我最终会得到一个 3x2 数组”:

    params =array([1,2,3]).reshape(3,1)
    curr_g =array([4,5,6]).reshape(3,1)
    print hstack((params, curr_g)).shape  # == (3,2)
    

    您可能会得到一个形状为(6,) 的数组,因为temp_g.paramsg 的形状都为(3,),而不是(3,1)。如果是这种情况,您最好使用column_stack((temp_g.params, curr_g))

    最后一点,您首先将您的大数组g 初始化为正确的大小:

    g=array((N,3,2))
    

    然后将其填充到 for 循环中:

    for j, (y, w) in enumerate(zip(z.T, weights.T)):
        #calculate temp_g and curr_g
        g[j]=column_stack((temp_g.params, curr_g))
    

    【讨论】:

    • 它似乎不起作用...我打印出 curr_g 的形状:(0L),我得到错误:return _nx.concatenate(arrays,1)... ValueError: all the input array dimensions except for the concatenation axis must match exactly
    • 你能发帖temp_g.params.shapecurr_g.shape吗?
    • temp_g.params 是 (3L,) 并且 curr_g.shape 是 (0L,)。但是我现在尝试的是像 curr_g = np.array([3,]) 这样初始化 curr_g。然后在循环中我说:if curr_g is None: curr_g = np.c_[temp_g.params, curr_g] else: curr_g = temp_g.params 在这种情况下,curr_g 确实以(3L,) 结束,但它并不能叠加。我希望它只有在它为空时才被分配temp_g,但它似乎正在做相反的事情......它只保存temp_g的当前值,但不与之前的值叠加。跨度>
    • 问题在于你如何计算curr_g,而不是如何将数组堆叠在一起。
    • 我不计算curr_g。当它为空时,我需要简单地为其分配temp_g 的值,当它不为空并且它已经包含以前的temp_g 时,我需要将新的temp_g 堆叠到它上面。 temp_g 总是被计算为 (3L,)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2018-06-05
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多