Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 225

Filling a dataframe with multiple dataframe values

I have some 100 dataframes that need to be filled in another big dataframe. Presenting the question with two dataframes

import pandas as pd
df1 = pd.DataFrame([1,1,1,1,1], columns=["A"])
df2 = pd.DataFrame([2,2,2,2,2], columns=["A"])

Please note that both the dataframes have same column names.

I have a master dataframe that has repetitive index values as follows:-

master_df=pd.DataFrame(index=df1.index)
master_df= pd.concat([master_df]*2)

Expected Output:-

master_df['A']=[1,1,1,1,1,2,2,2,2,2]

I am using for loop to replace every n rows of master_df with df1,df2... df100. Please suggest a better way of doing it. In fact df1,df2...df100 are output of a function where the input is column A values (1,2). I was wondering if there is something like

another_df=master_df['A'].apply(lambda x: function(x))

Thanks in advance.

Upvotes: 1

Views: 206

Answers (1)

Jose Avila
Jose Avila

Reputation: 221

If you want to concatenate the dataframes you could just use pandas concat with a list as the code below shows.

First you can add df1 and df2 to a list:

df_list = [df1, df2]

Then you can concat the dfs:

master_df = pd.concat(df_list)

I used the default value of 0 for 'axis' in the concat function (which is what I think you are looking for), but if you want to concatenate the different dfs side by side you can just set axis=1.

Upvotes: 2

Related Questions