如何在python中顺序填充3d矩阵?

时间:2018-06-13 15:38:20

标签: python list numpy numpy-ndarray

我有一个nd-array' A'尺寸(n,m,p)和I有一个长度为n * m的列表,其中包含数组a1,a2,..每个数组的长度为p。我要做的是按顺序(按行)填写“A'使用阵列' a'。例如,考虑以下示例:

A = np.empty ((2,3,4))

a1 = np.array([1,2,3,0])
a2 = np.array([3,4,6,9])
a3 = np.array([9,5,8,5])
a4 = np.array([1,5,4,2])
a5 = np.array([9,7,0,5])
a6 = np.array([4,3,2,1])
lst = [a1, a2, a3, a4, a5, a6]

我正试图找到一些方法

A = DoSomething(A, lst)
print(A)
array([[[ 1.,  2.,  3.,  0.],
        [ 3.,  4.,  6.,  9.],
        [ 9.,  5.,  8.,  5.]],
       [[ 1.,  5.,  4.,  2.],
        [ 9.,  7.,  0.,  5.],
        [ 4.,  3.,  2.,  1.]]])

所以这样A[0, 0, :]=a1, A[0, 1, :]=a2等等。

3 个答案:

答案 0 :(得分:1)

简单地做

A[0] = lst[:3]
A[1] = lst[3:]

以编程方式,我想这已经完成了

for index in range(A.shape[0]):
     A[index] = lst[A.shape[1]*index : A.shape[1]*(index + 1)]

或者只做

A = np.array(lst, dtype=float).reshape((2, 3, 4))

输出:

[[[1. 2. 3. 0.]
  [3. 4. 6. 9.]
  [9. 5. 8. 5.]]

 [[1. 5. 4. 2.]
  [9. 7. 0. 5.]
  [4. 3. 2. 1.]]]

答案 1 :(得分:1)

你可以用pythonic方式做到:

A=np.c_[lst].reshape((2,3,4))

这不需要初始化数组A

我不会包含其他解决方案,因为有循环只是冗余代码,而对于更大的数组则要慢得多。

答案 2 :(得分:1)

你可以做到

>>> A.reshape(len(lst), -1)[...] = lst
>>> A
array([[[1., 2., 3., 0.],
        [3., 4., 6., 9.],
        [9., 5., 8., 5.]],

       [[1., 5., 4., 2.],
        [9., 7., 0., 5.],
        [4., 3., 2., 1.]]])

升级范例的几个时间点:

>>> A = np.empty ((2000,300,40))
>>> lst = 100000*[l.repeat(10) for l in lst]
>>> 
>>> from timeit import timeit
>>> kwds = dict(globals=globals(), number=5)
>>> 
# my solution: fast, short, readable
>>> timeit("A.reshape(len(lst), -1)[...] = lst", **kwds)
0.8862412960734218
# @hpaulj's suggestion slow, very short, very readable
>>> timeit("A.flat[:] = lst", **kwds)
1.7412563359830528
# @FHTMitchell 1 fast, long, index-heavy
>>> timeit("for index in range(A.shape[0]): A[index] = lst[A.shape[1]*index : A.shape[1]*(index + 1)]", **kwds)0.8682223120704293
# @FHTMitchell 2 middling, short, very readable
>>> timeit("np.array(lst).reshape(A.shape)", **kwds)
1.0178500059992075
# @anishtain4 slow, short, misleading
>>> timeit("np.c_[lst].reshape(A.shape)", **kwds)
2.458487769123167