How to recover original indices for a flattened Numpy array?

后端 未结 6 467
逝去的感伤
逝去的感伤 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:27

    As hpaulj pointed out in a comment, I could add indexing=='ij' to the meshgrid call:

    A = np.random.rand(2,3,4)
    dimnames = ['z', 'y', 'x']
    ranges   = [ np.arange(x) for x in A.shape ]
    ix       = [ x.flatten()  for x in np.meshgrid(*ranges, indexing='ij') ]
    for name, col in zip(dimnames, ix):
        df[name] = col
    df = df.set_index(dimnames).squeeze()
    
    # Compare the results
    for ix, val in df.iteritems():
        print ix, val == A[ix]
    (0, 0, 0) True
    (0, 0, 1) True
    (0, 0, 2) True
    (0, 0, 3) True
    (0, 1, 0) True
    (0, 1, 1) True
    (0, 1, 2) True
    (0, 1, 3) True
    (0, 2, 0) True
    (0, 2, 1) True
    (0, 2, 2) True
    (0, 2, 3) True
    (1, 0, 0) True
    (1, 0, 1) True
    (1, 0, 2) True
    (1, 0, 3) True
    (1, 1, 0) True
    (1, 1, 1) True
    (1, 1, 2) True
    (1, 1, 3) True
    (1, 2, 0) True
    (1, 2, 1) True
    (1, 2, 2) True
    (1, 2, 3) True
    

提交回复
热议问题