1

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 message
TypeError: list indices must be integers or slices, not DataFrame

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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]

3 Comments

Thanks! This gave me an error "TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"" but this post helped me solve that problem!! link
@michan2378 Thanks for the information. I updated my answer with a fix for that error. This also leads me to a question...is there a reason you don't concatenate all of the dataframes together into a single dataframe?
yes, I am making a program where the training data for the model is conditional. In this case, dataframe "df" contains data used to train all model the same, and in addition to that, I want to add conditional data that is in dataframes "df1, df2, df3".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.