How to transform a 3d arrays into a dataframe in python

后端 未结 3 1083
再見小時候
再見小時候 2021-01-05 12:21

I have a 3d arrays as follows:

ThreeD_Arrays = np.random.randint(0, 1000, (5, 4, 3))

array([[[715, 226, 632],
        [305,  97, 534],
        [ 88, 592, 90         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-05 12:42

    You could convert your 3D array to a Pandas Panel, then flatten it to a 2D DataFrame (using .to_frame()):

    import numpy as np
    import pandas as pd
    np.random.seed(2016)
    
    arr = np.random.randint(0, 1000, (5, 4, 3))
    pan = pd.Panel(arr)
    df = pan.swapaxes(0, 2).to_frame()
    df.index = df.index.droplevel('minor')
    df.index.name = 'Date'
    df.index = df.index+1
    df.columns = list('ABC')
    

    yields

            A    B    C
    Date               
    1     875  702  266
    1     940  180  971
    1     254  649  353
    1     824  677  745
    ...
    4     675  488  939
    4     382  238  225
    4     923  926  633
    4     664  639  616
    4     770  274  378
    

    Alternatively, you could reshape the array to shape (20, 3), form the DataFrame as usual, and then fix the index:

    import numpy as np
    import pandas as pd
    np.random.seed(2016)
    
    arr = np.random.randint(0, 1000, (5, 4, 3))
    df = pd.DataFrame(arr.reshape(-1, 3), columns=list('ABC'))
    df.index = np.repeat(np.arange(arr.shape[0]), arr.shape[1]) + 1
    df.index.name = 'Date'
    print(df)
    

    yields the same result.

提交回复
热议问题