Vijayaraghavan
Vijayaraghavan

Reputation: 255

create column by append the column from the different dataframe in pandas

I have a list of data frame where I want to loop all the data frame and create the dataframe by append the column by filter the columns with the list provided. below is the code

#df_ls contains list of dataframes 
df_ls = [A, B, C, D]
for j in df_ls:
    match_ls = ['card', 'brave', 'wellness']
    for i in text:
        if i in j.columns:
            print(i)
        df1 = j[i]
        df2 = df1
        df_full = df2.append(df1)

Need the Result new dataframe with single column contains all the match_ls string value.

A 
card  banner
rex   23 
fex   45
jex   66

B
brave laminate
max   ste
vax   pre
jox   lex

expected output
rex
fex
jex
max
vax
jox

Upvotes: 2

Views: 54

Answers (1)

jezrael
jezrael

Reputation: 862481

Use list comprehension with filter columns names by Index.intersection and last use concat for join together:

df_ls = [A, B, C, D]
match_ls = ['card', 'brave', 'wellness']
dfs = [j[j.columns.intersection(match_ls)].stack().reset_index(drop=True) for j in df_ls]
df_full = pd.concat(dfs, ignore_index=True)

Loop version:

dfs = []
for j in df_ls:
    df = j[j.columns.intersection(match_ls)].stack().reset_index(drop=True) 
    print (df)
    dfs.append(df)

df_full = pd.concat(dfs, ignore_index=True)
print (df_full)

Upvotes: 3

Related Questions