Home > Net >  How can we convert pandas dataframe two columns to python list after merging two columns vertically?
How can we convert pandas dataframe two columns to python list after merging two columns vertically?

Time:03-01

I have a dataframe...

print(df)       
Name    ae_rank    adf      de_rank
a       1          lk       4   
b       2          lp       5
c       3          yi       6

How can I concat ae_rank column and de_rank column vertically and convert them into python list.

Expectation...

my_list = [1, 2, 3, 4, 5, 6]

CodePudding user response:

Simpliest is join lists:

my_list =  df['ae_rank'].tolist()   df['de_rank'].tolist()

If need reshape DataFrame with DataFrame.melt:

my_list = df.melt(['Name','adf'])['value'].tolist()
print (my_list )
[1, 2, 3, 4, 5, 6]

CodePudding user response:

Another option is

my_list = df[['ae_rank', 'de_rank']].T.stack().tolist()
#[1, 2, 3, 4, 5, 6]

CodePudding user response:

Most efficiently, use filter to select the columns by name that include "_rank" and use the underlying numpy array with ravel on the 'F' order (column major order):

my_list = df.filter(like='_rank').to_numpy().ravel('F').tolist()

output: [1, 2, 3, 4, 5, 6]

  • Related