concatenate dataframe with dataframe from list

Question:

I want to concatenate a dataframe (df) with another dataframe that is stored in a list of dataframes.

dflist = [df1, df2, df3]

What I want is a dataframe like below

new_dflist = [df+df1, df+df2, df+df3]

new_dflist=[]
for n in dflist:
    new_dflist.append(pd.concat(df, dflist[n]))

but I get the error,
TypeError: list indices must be integers or slices, not DataFrame

I also tried with enumerate but I get the error,
TypeError: list indices must be integers or slices, not tuple

Asked By: michan2378

||

Answers:

Try this:

dflist = [df1, df2, df3]
new_dflist=[]
for n in dflist:
    new_dflist.append(pd.concat(df, n))

n is a dataframe and you are trying to put it in list index

Answered By: Talha Tayyab

but I get the error, TypeError: list indices must be integers or slices, not DataFrame

That is because n is a dataframe, not an integer. You seem to think that for loop gives you the indexes in a list, but it actually gives you the items directly. Just change your code to use the dataframe from the for loop iterator:

new_dflist=[]
for new_df in dflist:
    new_dflist.append(pd.concat([df, new_df]))

Alternatively, you can do this in a single line with a list comprehension:

new_dflist=[pd.concat(df, new_df) for new_df in dflist]
Answered By: Code-Apprentice
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.