How to create a new dataframe with every iteration of for loop in Python

11,423

You should make up your question so that other people will get max advantage from this site.

I will try to propose solution to this question.

On every iteration I want create a new data frame, How?

The idea is to store the dataframes as values of a dictionary.

cnt = 22  # your loop
dict_of_df = {} # initialize empty dictionary

for i in range(0,22):
    newname = df_sheetnames['col'].values[i]
    dict_of_df["df_{}".format(i)] = pd.read_excel('DATA.xlsx', sheetname=newname, skiprows=6, usecols=[14,15,16])

You can access the dataframes by call dict_of_df[key], where key = "df_1", "df_2", ... , "df_22"

Now you have many dataframes and you want to concat, use pandas.concat()

If you want to rename the columns after that, simply write complete_df.columns = ['col1', 'col2', 'col3', ...]

Share:
11,423

Related videos on Youtube

user9023836
Author by

user9023836

Updated on June 04, 2022

Comments

  • user9023836
    user9023836 almost 2 years

    Click here to see image

    #### the data is inverted #######
    
    #### To bring back to its original position ####### 
       df_1= df_i.iloc[::-1]
    
    #### Set index again ###################
    df_1.index = range(len(df_1.index))
    

    enter image description here

    #

    In for I am creating a data frame df , But I want the data frame name as df_0, df_1, df_2 .......................... df_n

    On every iteration I want create a new data frame, How?

    And my count = 22, That means my loop will run for 22 times.

    Is there a way that I concat horizontally all the data frames as a single dta frame

    14, 15, 16 (from first sheet), 14A, 15A, 16A (from second Sheet), 14B,15B, 16B,(From Third sheet) as col1, col2, col3,col4.......................

    Appreciate your help

    • petezurich
      petezurich over 5 years
      Welcome to SO. Please proofread your questions and learn how to properly format (especially your code). Please also post your code inline and never as images. Thanks!
  • ipramusinto
    ipramusinto over 5 years
    @user9023836, I'm happy if it helped. You can accept the answer by turning the check mark green or upvote. :D