使用
这个可以工作。
这不会。
应返回
具有以下功能:
给我以下的结果。
np.diag
,我可以构造一个二维数组,在对角线上输入一个一维数组。但是如果我有n维数组作为输入,怎么做呢?这个可以工作。
foo = np.random.randint(2, size=(36))
print foo
print np.diag(foo)
[1 1 1 1 1 1 0 1 0 0 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 1 1 0]
[[1 0 0 ..., 0 0 0]
[0 1 0 ..., 0 0 0]
[0 0 1 ..., 0 0 0]
...,
[0 0 0 ..., 1 0 0]
[0 0 0 ..., 0 1 0]
[0 0 0 ..., 0 0 0]]
这不会。
foo = np.random.randint(2, size=(2,36))
print foo
[[1 1 0 1 1 0 1 1 1 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0]
[0 1 1 1 0 0 1 1 1 1 0 1 0 1 0 1 0 0 0 0 1 0 1 1 1 1 0 0 1 0 1 1 1 1 0 1]]
do_something(foo)
应返回
array([[[ 1., 0., 0., ..., 0., 0., 0.],
[ 0., 1., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
...,
[ 0., 0., 0., ..., 1., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.]],
[[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 1., 0., ..., 0., 0., 0.],
[ 0., 0., 1., ..., 0., 0., 0.],
...,
[ 0., 0., 0., ..., 1., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 1.]]])
编辑
这篇文章基于Alan和ajcr在这篇帖子中的回答,以及Saulo Castro和jaime的贡献,其中ajcr提到了链接。通常情况下,一切都取决于您的输入。我的输入通常具有以下形式:
M = np.random.randint(2, size=(1000, 36))
具有以下功能:
def Alan(M):
M = np.asarray(M)
depth, size = M.shape
x = np.zeros((depth,size,size))
for i in range(depth):
x[i].flat[slice(0,None,1+size)] = M[i]
return x
def ajcr(M):
return np.eye(M.shape[1]) * M[:,np.newaxis,:]
def Saulo(M):
b = np.zeros((M.shape[0], M.shape[1], M.shape[1]))
diag = np.arange(M.shape[1])
b[:, diag, diag] = M
return b
def jaime(M):
b = np.zeros((M.shape[0], M.shape[1]*M.shape[1]))
b[:, ::M.shape[1]+1] = M
return b.reshape(M.shape[0], M.shape[1], M.shape[1])
给我以下的结果。
%timeit Alan(M)
100 loops, best of 3: 2.22 ms per loop
%timeit ajcr(M)
100 loops, best of 3: 5.1 ms per loop
%timeit Saulo(M)
100 loops, best of 3: 4.33 ms per loop
%timeit jaime(M)
100 loops, best of 3: 2.07 ms per loop
foo
很大,这可能会变得很昂贵。 - Alan