变量赋值:保持形状

时间:2013-01-19 19:28:16

标签: python numpy

...更好地直接显示代码。这是:

import numpy as np
a = np.zeros([3, 3])
a
array([[ 0., 0., 0.],
       [ 0., 0., 0.],
       [ 0., 0., 0.]])
b = np.random.random_integers(0, 100, size = (1, 3))
b
array([[ 10,  3,  8]])
c = np.random.random_integers(0, 100, size = (4, 3))
c
array([[ 22, 21, 14],
       [ 55, 64, 12],
       [ 33, 85, 98],
       [ 37, 44, 45]])
a = b  will change dimensions of a
a = c  will change dimensions of a

对于a = b,我想:

array([[ 10.,  3.,  8.],
       [  0.,  0.,  0.],
       [  0.,  0.,  0.]])

对于a = c,我想要:

array([[ 22, 21, 14],
       [ 55, 64, 12],
       [ 33, 85, 98]])

所以我想锁定'a'的形状,以便分配给它的值在必要时被“裁剪”。当然没有if语句。

2 个答案:

答案 0 :(得分:1)

您可以使用Numpy slice notation轻松完成此操作。 Here是一个SO问题,有很好的答案可以清楚地解释它。基本上,您需要确保左侧数组和右侧的形状具有数组匹配,并且您可以通过适当地切割相应的数组来实现此目的。

import numpy as np
a = np.zeros([3, 3])
b = np.array([[ 10,  3,  8]])
c = np.array([[ 22, 21, 14],
       [ 55, 64, 12],
       [ 33, 85, 98],
       [ 37, 44, 45]])

a[0] = b
print a
a = c[0:3]
print a

输出:

[[ 10.   3.   8.]
 [  0.   0.   0.]
 [  0.   0.   0.]]
[[22 21 14]
 [55 64 12]
 [33 85 98]]

似乎您想要使用来自第二个2D阵列的元素替换2D数组左上角的元素,而不必担心数组的大小。这是一种方法:

def replacer(orig, repl):
    new = np.copy(orig)
    w2, h1 = new.shape
    w1, h2 = repl.shape
    new[0:min(w1,w2), 0:min(h1,h2)] = repl[0:min(w1,w2), 0:min(h1,h2)]
    return new
print replacer(a,b)
print replacer(a,c)

答案 1 :(得分:1)

问题在于,相等的运算符正在制作数组的浅表副本,而你想要的是数组部分的深层副本。

因此,如果你知道b只有一个外部数组,那么你可以这样做:

a[0] = b

如果知道a是3x3,那么你也可以这样做:

a = c[0:3]

此外,如果您希望它们是实际的深层副本,您需要:

a[0] = b.copy()

a = c[0:3].copy()

让他们独立。

如果您还不知道矩阵的长度,可以使用len()函数在运行时查找。