Home > database >  Merge a list of dataframes to create one dataframe by selecting last column only
Merge a list of dataframes to create one dataframe by selecting last column only

Time:12-11

I have a list of dataframes

new_list=[df1,df2,df3]

I know the follwoing command to merge

pd.concat(new_list, axis=1)

How to create a dataframe by selcting last columns of all dataframes from the list without using for loops

CodePudding user response:

Pick the last columns using map:

import pandas as pd

# This is to have a test list to use
df1 = pd.DataFrame({"a":[1,2,3], "b":[2,3,4]})
df2 = pd.DataFrame({"c":[1,2,3], "d":[2,3,4]})
new_list = [df1, df2]

# logic
pd.concat(map(lambda x:x[x.columns[-1]], new_list), axis=1)

OUTPUT

   b  d
0  2  2
1  3  3
2  4  4

CodePudding user response:

Do use this

import pandas as pd
new_list = [df1.iloc[:,-1:], df2.iloc[:,-1:], df3.iloc[:,-1:]]
pd.concat(new_list, axis = 1)

CodePudding user response:

You can also use lambda :

import pandas as pd
func = lambda x: x.iloc[:, -1] #select all rows and last column
new_list = [func(df1), func(df2), func(df3)]
pd.concat(new_list, axis=1)
  • Related