How to recover original indices for a flattened Numpy array?

后端 未结 6 455
逝去的感伤
逝去的感伤 2021-01-02 19:49

I\'ve got a multidimensional numpy array that I\'m trying to stick into a pandas data frame. I\'d like to flatten the array, and create a pandas index that reflects the pre-

6条回答
  •  时光取名叫无心
    2021-01-02 20:28

    My solution is based on this this answer by Divakar involving np.ogrid. This function should work for any array of any dimension.

    def indices_merged_arr(arr):
        n = arr.ndim
        grid = np.ogrid[tuple(map(slice, arr.shape))]
        out = np.empty(arr.shape + (n+1,), dtype=arr.dtype)
        for i in range(n):
            out[...,i+1] = grid[i]
        out[...,0] = arr
        out.shape = (-1,n+1)
        return out
    
    A = np.array([[[ 0.43793885,  0.40078139,  0.48078691,  0.05334248],
                   [ 0.76331509,  0.82514441,  0.86169078,  0.86496111],
                   [ 0.75572665,  0.80860943,  0.79995337,  0.63123724]],
    
                  [[ 0.20648946,  0.57042315,  0.71777265,  0.34155005],
                   [ 0.30843717,  0.39381407,  0.12623462,  0.93481552],
                   [ 0.3267771 ,  0.64097038,  0.30405215,  0.57726629]]])
    
    df = pd.DataFrame(indices_merged_arr(A), columns=list('Axyz'))
    df
    
               A    x    y    z
    0   0.437939  0.0  0.0  0.0
    1   0.400781  0.0  0.0  1.0
    2   0.480787  0.0  0.0  2.0
    3   0.053342  0.0  0.0  3.0
    4   0.763315  0.0  1.0  0.0
    5   0.825144  0.0  1.0  1.0
    6   0.861691  0.0  1.0  2.0
    7   0.864961  0.0  1.0  3.0
    8   0.755727  0.0  2.0  0.0
    9   0.808609  0.0  2.0  1.0
    10  0.799953  0.0  2.0  2.0
    11  0.631237  0.0  2.0  3.0
    12  0.206489  1.0  0.0  0.0
    13  0.570423  1.0  0.0  1.0
    14  0.717773  1.0  0.0  2.0
    15  0.341550  1.0  0.0  3.0
    16  0.308437  1.0  1.0  0.0
    17  0.393814  1.0  1.0  1.0
    18  0.126235  1.0  1.0  2.0
    19  0.934816  1.0  1.0  3.0
    20  0.326777  1.0  2.0  0.0
    21  0.640970  1.0  2.0  1.0
    22  0.304052  1.0  2.0  2.0
    23  0.577266  1.0  2.0  3.0
    

提交回复
热议问题