假设您有一个数组(m,m)并且想要使它成为(n,n)。例如,将2x2矩阵转换为6x6。所以:Python:将尺寸添加到二维数组
[[ 1. 2.]
[ 3. 4.]]
要:
[[ 1. 2. 0. 0. 0. 0.]
[ 3. 4. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]]
这是我在做什么:
def array_append(old_array, new_shape):
old_shape = old_array.shape
dif = np.array(new_shape) - np.array(old_array.shape)
rows = []
for i in xrange(dif[0]):
rows.append(np.zeros((old_array.shape[0])).tolist())
new_array = np.append(old_array, rows, axis=0)
columns = []
for i in xrange(len(new_array)):
columns.append(np.zeros(dif[1]).tolist())
return np.append(new_array, columns, axis=1)
使用例:
test1 = np.ones((2,2))
test2 = np.zeros((6,6))
print array_append(test1, test2.shape)
输出:
[[ 1. 1. 0. 0. 0. 0.]
[ 1. 1. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]]
根据this答案。但是对于简单的操作来说,这是很多代码。有一个更简洁/ pythonic的方式来做到这一点?
@pnodnda:你的做法是太复杂了。只需分配新阵列并将旧的副本复制到适当的位置即可。就是这么简单,正如Benjamins(已修改)和我的回答所证明的那样。顺便说一句,追加单词通常与动态数据结构相关联,而`numpy.array`不是。谢谢 – eat 2011-02-01 21:27:08