【发布时间】:2011-02-01 21:04:04
【问题描述】:
假设你有一个数组 (m, m) 并且想要使它成为 (n, n)。例如,将 2x2 矩阵转换为 6x6。所以:
[[ 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不是。谢谢