Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

how to create dataframe with for loop in rows

  1. User

    how to create dataframe with for loop in rows

  2. Assistant

    Here is an example of how to create a dataframe with for loop in rows using Python pandas library:

    import pandas as pd
    
    # Define an empty dataframe
    df = pd.DataFrame(columns=['Name', 'Age', 'Gender', 'City'])
    
    # Define list of details
    details = [['John', 25, 'Male', 'New York'],
               ['Alex', 30, 'Male', 'Los Angeles'],
               ['Mary', 28, 'Female', 'Chicago'],
               ['Rachel', 22, 'Female', 'San Francisco']]
    
    # Iterate through the rows in the list of details and append them to the empty dataframe
    for row in details:
        df = df.append(pd.Series(row, index=['Name', 'Age', 'Gender', 'City']), ignore_index=True)
    
    # Print the dataframe
    print(df)
    

    Output:

         Name Age  Gender           City
    0    John  25    Male       New York
    1    Alex  30    Male    Los Angeles
    2    Mary  28  Female        Chicago
    3  Rachel  22  Female  San Francisco
    

    In this code, we first create an empty dataframe with specific column headers using the pd.DataFrame() method. Then we define a list of rows containing the data to be added to the dataframe.

    We use a for loop to iterate through each row in the list of details and add it to the dataframe using the df.append() method. We pass pd.Series(row, index=['Name', 'Age', 'Gender', 'City']) as an argument to df.append() to create a new row with the data from the current iteration. Finally, we set ignore_index=True to reset the index of the dataframe.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.