扩展numpy数组维度并重塑

时间:2019-05-13 11:39:32

标签: python arrays numpy

所以我有一个numpy数组,其中包含:

function createTree(arr, topItem = 'Top') {
    const node = (name, parent = null) => ({name, parent, children: []});
    const addNode = (parent, child) => {
        parent.children.push(child);

        return child;
    };
    const findNamedNode = (name, parent) => {
        for(const child of parent.children) {
            if(child.name === name) { return child; }
            const found = findNamedNode(name, child);
            if(found) { return found; }
        }
    };

    const top = node(topItem);
    let current;

    for(const children of arr) {
        current = top;
        for(const name of children) {
            const found = findNamedNode(name, current);
            current = found ? found : addNode(current,
                node(name, current.name));
        }
    }

    return top;
}

当我执行时:

arr =  [1 2 3 4 5 6]

它给了我

print(arr.shape)

我正在尝试添加常数3

(6,)

进入数组的维度,这样我将获得:

 const_val = 3

首先,我尝试通过以下方式扩展数组的维度:

(6,3)

现在在哪里:

arr = np.expand_dims(arr, axis = -1)

还给我:

print(arr.shape)

但是,当我尝试调整数组维数以将1替换为常数3时,

(6,1)

我收到错误消息:

arr = np.reshape(arr, (arr.shape[0], const_val))

我可以知道为什么会这样吗?

3 个答案:

答案 0 :(得分:0)

是否要向阵列中添加两个空列?在这种情况下,您可以连接大小为(6,2)的矩阵:

arr = np.array([1,2,3,4,5,6]).reshape(6,1)
to_add = np.zeros((6,2))
res = np.concatenate((arr, to_add), axis=1)

答案 1 :(得分:0)

当从(6,1)重塑为(6,3)时,您需要“输入一些值”,因为从6项变为18。您是否要使两个新列与第一个相同?在这种情况下,将numpy.tile用作:

arr_6_3 = np.tile(arr, (1,3))

答案 2 :(得分:0)

如果我正确理解您的要求,那么以下解决方案就是您需要的解决方案:

In [63]: const_val = 3

In [64]: new_shape = (arr.shape[0], const_val)

In [65]: arr_new = np.array(np.broadcast_to(arr[:, None], new_shape))

In [66]: arr_new
Out[66]: 
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6]])

In [67]: arr_new.shape
Out[67]: (6, 3)

另一方面,如果您只想将同一数组复制到新形状,则使用:

header('Access-Control-Allow-Origin: *');
相关问题