Reshape a pandas DataFrame of (720, 720) into (518400, ) 2D into 1D

前端 未结 1 881
走了就别回头了
走了就别回头了 2021-01-23 05:22

I have a DataFrame with shape: 720*720 2D. I wanna convert it to 1D dimension without changing its values. How can I do this using Pandas?

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 05:49

    Use numpy.ravel with converted DataFrame to numpy array:

    np.random.seed(123)
    df = pd.DataFrame(np.random.randint(10, size=(3,3)))
    print (df)
       0  1  2
    0  2  2  6
    1  1  3  9
    2  6  1  0
    
    out = df.values.ravel('F')
    #alternative for pandas 0.24+
    #out = df.to_numpy().ravel('F')
    print (out)
    [2 1 6 2 3 1 6 9 0]
    
    s = pd.Series(df.values.ravel('F'))
    #alternative for pandas 0.24+
    #s = pd.Series(df.to_numpy().ravel('F'))
    print (s)
    0    2
    1    1
    2    6
    3    2
    4    3
    5    1
    6    6
    7    9
    8    0
    dtype: int32
    

    0 讨论(0)
提交回复
热议问题