1

I'm trying create multiple data frames from a single data-frame. I managed to achieve the process by repeating the same line of code, but its looks tedious and is not time friendly. I want to create a loop that iterates through the data-frame and create dataframes for me. Also I have a list of copy of my Intial dataframe(from which I want to create multiple dataframes).

df_list = [df_0run,df_1run,df_2run,df_3run,df_4run,df_5run,df_6run]

Please suggest an approach for my question.

df_0season1=df_0run.loc[df_0run['Season_Id']==1]
df_0season2=df_0run.loc[df_0run['Season_Id']==2]
df_0season3=df_0run.loc[df_0run['Season_Id']==3]
df_0season4=df_0run.loc[df_0run['Season_Id']==4]
df_0season5=df_0run.loc[df_0run['Season_Id']==5]
df_0season6=df_0run.loc[df_0run['Season_Id']==6]
df_0season7=df_0run.loc[df_0run['Season_Id']==7]
df_0season8=df_0run.loc[df_0run['Season_Id']==8]
df_0season9=df_0run.loc[df_0run['Season_Id']==9]

In this fashion I want to create multiple dataframes, and return them as a list. or multiple lists.

Required output

Seasons list = [df_0season1,df_0season2,df_0season3,df_0season4,df_0season5,df_0season6,df_0season7,df_0season8,df_0season9, 
df_1season1,df_1season2,df_1season3,df_1season4,df_1season5,df_1season6,df_1season7,df_1season8,df_1season9, 
df_2season1,df_2season2,df_2season3,df_2season4,df_2season5,df_2season6,df_2season7,df_2season8,df_2season9, 
df_3season1,df_3season2,df_3season3,df_3season4,df_3season5,df_3season6,df_3season7,df_3season8,df_3season9, 
df_4season1,df_4season2,df_4season3,df_4season4,df_4season5,df_4season6,df_4season7,df_4season8,df_4season9,
 df_5season1,df_5season2,df_5season3,df_5season4,df_5season5,df_5season6,df_5season7,df_5season8,df_5season9]

1 Answer 1

2

I think you can use a little help of exec over here,

for i in range (1,10):
    exec("""df_0season{}=df_0run.loc[df_0run['Season_Id']=={}]""".format(i))

This is just a basic application of exec and you can modify it as your requirement.

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

1 Comment

Worked like a charm. Thank you very much. But the list holds entire dataframe with the data, is there a way to store the datafram into a name say df_0season1

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.