Converting a 3D List to a 3D NumPy array

前端 未结 5 1077
北海茫月
北海茫月 2021-01-18 16:19

Currently, I have a 3D Python list in jagged array format.
A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]

Is there any way I could convert

5条回答
  •  梦毁少年i
    2021-01-18 16:40

    It we turn your list into an array, we get a 2d array of objects

    In [1941]: A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]
    In [1942]: A = np.array(A)
    In [1943]: A.shape
    Out[1943]: (2, 3)
    In [1944]: A
    Out[1944]: 
    array([[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
           [[0], [0], [0]]], dtype=object)
    

    When I try A+1 it iterates over the elements of A and tries to do +1 for each. In the case of numeric array it can do that in fast compiled code. With an object array it has to invoke the + operation for each element.

    In [1945]: A+1
    ...
    TypeError: can only concatenate list (not "int") to list
    

    Lets try that again with a flat iteration over A:

    In [1946]: for a in A.flat:
          ...:     print(a+1)
    ....
    TypeError: can only concatenate list (not "int") to list
    

    The elements of A are lists; + for a list is a concatenate:

    In [1947]: for a in A.flat:
          ...:     print(a+[1])
          ...:     
    [0, 0, 0, 1]
    [0, 0, 0, 1]
    [0, 0, 0, 1]
    [0, 1]
    [0, 1]
    [0, 1]
    

    If the elements of A were themselves arrays, I think the +1 would work.

    In [1956]: for i, a in np.ndenumerate(A):
          ...:     A[i]=np.array(a)
          ...:     
    In [1957]: A
    Out[1957]: 
    array([[array([0, 0, 0]), array([0, 0, 0]), array([0, 0, 0])],
           [array([0]), array([0]), array([0])]], dtype=object)
    In [1958]: A+1
    Out[1958]: 
    array([[array([1, 1, 1]), array([1, 1, 1]), array([1, 1, 1])],
           [array([1]), array([1]), array([1])]], dtype=object)
    

    And to get back to the pure list form, we have apply tolist to both the elements of the object array and to the array itself:

    In [1960]: A1=A+1
    In [1961]: for i, a in np.ndenumerate(A1):
          ...:     A1[i]=a.tolist()
    
    In [1962]: A1
    Out[1962]: 
    array([[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
           [[1], [1], [1]]], dtype=object)
    In [1963]: A1.tolist()
    Out[1963]: [[[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1], [1], [1]]]
    

    This a rather round about way of adding a value to all elements of nested lists. I could have done that with one iteration:

    In [1964]: for i,a in np.ndenumerate(A):
          ...:     A[i]=[x+1 for x in a]
          ...:     
    In [1965]: A
    Out[1965]: 
    array([[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
           [[1], [1], [1]]], dtype=object)
    

    So doing math on object arrays is hit and miss. Some operations do propagate to the elements, but even those depend on how the elements behave.

提交回复
热议问题