交织3个numpy矩阵?

时间:2017-03-14 15:46:01

标签: python numpy matrix

我如何沿着columwise交织numpy矩阵。

给出了这个例子:

>>> import numpy as np
>>> a = np.zeros((3,3))
>>> b = np.ones((3,3))
>>> c = b*2

交织输出应

[[ a[0,0].  b[0,0].  c[0,0].  a[0,1]  b[0,1]  c[0,1] .. ]
 [ a[1,0].  b[1,0].  c[1,0].  a[1,1]  b[1,1]  c[1,1] .. ]
 [ a[2,0].  b[2,0].  c[2,0].  a[2,1]  b[2,1]  c[2,1] .. ]]

结束形状应为(3,9)

2 个答案:

答案 0 :(得分:4)

另一种选择,你可以使用tt.addTextChangedListener(new TextWatcher() { final String FUNCTION = "function"; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { int index = s.toString().indexOf(FUNCTION); if (index >= 0) { s.setSpan( new ForegroundColorSpan(Color.GREEN), index, index + FUNCTION.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } }); ,根据 docs dstack堆栈数组顺序深度(沿第三轴)所以它可以是方便这种情况:

np.dstack + reshape

一些样本数据不那么模糊:

np.dstack([a, b, c]).reshape(3,-1)
#array([[ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.],
#       [ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.],
#       [ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.]])

答案 1 :(得分:2)

如果所有矩阵具有相同的维度,您可以使用:

np.array([a,b,c]).transpose(1,2,0).reshape(3,-1)

或者合并 n 矩阵的通用函数:

def merge(*args):
    (m,_) = args[0].shape
    return np.array(args).transpose(1,2,0).reshape(m,-1)

(并使用merge(a,b,c)调用)

您甚至可以让它适用于任意维度,并使用:

def merge_arbitrary(*args):
    (*m,_) = args[0].shape
    return np.array(args).transpose(tuple(range(1,len(m)+2))+(0,)). \
                          reshape(m+[-1])

代码的工作原理如下。我们首先构造一个3×3×3矩阵,其形状为:

array([[[ a00,  a01,  a02],
        [ a10,  a11,  a12],
        [ a20,  a21,  a22]],

       [[ b00,  b01,  b02],
        [ b10,  b11,  b12],
        [ b20,  b21,  b22]],

       [[ c00,  c01,  c02],
        [ c10,  c11,  c12],
        [ c20,  c21,  c22]]])

接下来,我们制作一个transpose(1,2,0),以便现在[aij,bij,cij]是最低维度。所以从现在开始矩阵就有了形状:

array([[[a00, b00, c00],
        [a01, b01, c01],
        [a02, b02, c02]],

       [[a10, b10, c10],
        [a11, b11, c11],
        [a12, b12, c12]],

       [[a20, b20, c20],
        [a21, b21, c21],
        [a22, b22, c22]]])

最后通过调用reshape(3,-1),我们“删除”最低维度并连接:

array([[a00, b00, c00, a01, b01, c01, a02, b02, c02],
       [a10, b10, c10, a11, b11, c11, a12, b12, c12],
       [a20, b20, c20, a21, b21, c21, a22, b22, c22]])