Convert a Pandas DataFrame into a single row DataFrame

前端 未结 4 2008
情深已故
情深已故 2021-01-13 08:52

I\'ve seen similar questions but mine is more direct and abstract.

I have a dataframe with \"n\" rows, being \"n\" a small number.We can assume the index is just the

4条回答
  •  半阙折子戏
    2021-01-13 09:31

    We need stack and swaplevel

    df1=df.stack().swaplevel()
    df1.index=df1.index.map('{0[0]}_{0[1]}'.format) 
    df1.to_frame().T
    Out[527]: 
       A_0  B_0  C_0  D_0  E_0  A_1  B_1  C_1  D_1  E_1  A_2  B_2  C_2  D_2  E_2
    0    1    2    3    4    5    6    7    8    9   10   11   12   13   14    5
    

    Or you can using numpy

    pd.DataFrame(data=np.concatenate(df.values),index=[m+'_'+str(n) for m,n in zip(df.columns.tolist()*3,np.repeat([1,2,3],df.shape[1]))]).T
    Out[551]: 
       A_1  B_1  C_1  D_1  E_1  A_2  B_2  C_2  D_2  E_2  A_3  B_3  C_3  D_3  E_3
    0    1    2    3    4    5    6    7    8    9   10   11   12   13   14    5
    

提交回复
热议问题