Home > database >  how to change rows to column in python
how to change rows to column in python

Time:07-11

I want to convert my dataframe rows to column and take last value of last column.

here is my dataframe

df=pd.DataFrame({'flag_1':[1,2,3,1,2,500],'dd':[1,1,1,7,7,8],'x':[1,1,1,7,7,8]})
print(df)

   flag_1  dd  x
0       1   1  1
1       2   1  1
2       3   1  1
3       1   7  7
4       2   7  7
5     500   8  8

df_out:
   1 2 3 1 2 500 1 1 1 7 7 8 8

CodePudding user response:

Assuming you want a list as output, you can mask the initial values of the list column and stack:

import numpy as np
out = (df
 .assign(**{df.columns[-1]: np.r_[[pd.NA]*(len(df)-1),[df.iloc[-1,-1]]]})
 .T.stack().to_list()
 )

Output:

[1, 2, 3, 1, 2, 500, 1, 1, 1, 7, 7, 8, 8]

For a wide dataframe with a single row, use .to_frame().T in place of to_list() (here with a MultiIndex):

  flag_1                  dd                 x
       0  1  2  3  4    5  0  1  2  3  4  5  5
0      1  2  3  1  2  500  1  1  1  7  7  8  8
  • Related