简体   繁体   English

np.ndarray 的增量维度

[英]increment dimension of np.ndarray

I want to increment the dimension of an ndarray like this:我想像这样增加 ndarray 的维度:

from r = [[1 2]
          [3 4]] 

to r = [[1 2 0]
        [3 4 0]
        [0 0 0]]

if I use r.resize((3, 3), refcheck=False) i get:如果我使用 r.resize((3, 3), refcheck=False) 我得到:

[[1 2 3]
 [4 0 0]
 [0 0 0]]

Use NumPy's pad function:使用 NumPy 的pad功能:

import numpy as np
np.pad(r,(0,1))

This will pad with zeros r with padding size of 1 at the end of the rows and columns, and will not pad at the beginning (as we set to 0 the padding size there).这将在行和列的末尾填充零r ,填充大小为 1,并且不会在开头填充(因为我们将那里的填充大小设置为 0)。

You simply can define a new nparray and map the old one to it:您只需定义一个新的 nparray 并将旧的映射到它:

x = np.array([[1, 2], [3, 4]])

reshaped_array = np.zeros((3, 3))
reshaped_array[:2, :2] = x

output:输出:

array([[1., 2., 0.],
       [3., 4., 0.],
       [0., 0., 0.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM