Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

how to insert a row in dataframe

  1. User

    how to insert a row in dataframe

  2. Assistant

    Inserting a row into a DataFrame in pandas can be done in several ways. Below are a few techniques:

    Using loc[]

    This method allows you to insert a row at a specified index position.

    import pandas as pd
    
    # Sample DataFrame
    df = pd.DataFrame({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
    })
    
    # New row to insert
    new_row = {'A': 10, 'B': 20}
    
    # Insert the new row at index position 1
    df.loc[1.5] = new_row
    
    # Sort the index to restore proper order (if necessary)
    df = df.sort_index().reset_index(drop=True)
    
    print(df)
    

    Using append()

    append() creates a new DataFrame with the new row added at the end.

    import pandas as pd
    
    # Sample DataFrame
    df = pd.DataFrame({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
    })
    
    # New row to insert
    new_row = {'A': 10, 'B': 20}
    
    # Append the new row to the DataFrame
    df = df.append(new_row, ignore_index=True)
    
    print(df)
    

    Using concat()

    concat() can be used to concatenate two DataFrames.

    import pandas as pd
    
    # Sample DataFrame
    df = pd.DataFrame({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
    })
    
    # New row to insert
    new_row = pd.DataFrame({'A': [10], 'B': [20]})
    
    # Concatenate the DataFrames
    df = pd.concat([df.iloc[:2], new_row, df.iloc[2:]]).reset_index(drop=True)
    
    print(df)
    

    Using iloc[]

    This method allows you to insert a row at a specific position using integer-location based indexing.

    import pandas as pd
    
    # Sample DataFrame
    df = pd.DataFrame({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
    })
    
    # Row to be inserted
    new_row = {'A': 10, 'B': 20}
    insert_position = 1
    
    # Split the DataFrame and concatenate
    df = pd.concat([
        df.iloc[:insert_position],
        pd.DataFrame([new_row]),
        df.iloc[insert_position:]
    ]).reset_index(drop=True)
    
    print(df)
    

    Note:

    • Methods like append() and concat() do not modify the original DataFrame in-place; they return a new DataFrame.
    • The append() method has been deprecated in newer versions of pandas and will be removed in future versions. Hence, it's better to use concat() for future-proof code.