Flatten numpy array but also keep index of value positions?

前端 未结 9 1266
北荒
北荒 2021-02-04 13:58

I have several 2D numpy arrays (matrix) and for each one I would like to convert it to vector containing the values of the array and a vector containing each row/column index.

9条回答
  •  囚心锁ツ
    2021-02-04 14:11

    You can try this using itertools

    import itertools
    import numpy as np
    import pandas as pd
    
    def convert2dataframe(array):
        a, b = array.shape
        x, y = zip(*list(itertools.product(range(a), range(b))))
        df = pd.DataFrame(data={'V':array.ravel(), 'x':x, 'y':y})
        return df
    

    This works for arrays of any shape, not necessarily square matrices.

提交回复
热议问题