Python Pandas - How to append rows to a DataFrame


To append rows to a DataFrame, use the append() method. Here, we will create two DataFrames and append one after the another.

At first, import the pandas library with an alias −

import pandas as pd

Now, create the 1st DataFrame

dataFrame1 = pd.DataFrame(
   {
"Car": ['BMW', 'Lexus', 'Audi', 'Jaguar']

}
)

Create the 2nd DataFrame

dataFrame2 = pd.DataFrame(
{
"Car": ['Mercedes', 'Tesla', 'Bentley', 'Mustang']

}
)

Next, append rows to the end

dataFrame1 = dataFrame1.append(dataFrame2)

Example

Following is the code

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Jaguar']

}
)

print"DataFrame1 ...\n",dataFrame1

# Find length of DataFrame1
print"DataFrame1 length = ", len(dataFrame1)

# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['Mercedes', 'Tesla', 'Bentley', 'Mustang']

}
)

print"\nDataFrame2 ...\n",dataFrame2

# Find length of DataFrame2
print"DataFrame2 length = ", len(dataFrame2)

# append DataFrames
dataFrame1 = dataFrame1.append(dataFrame2)
print"\nAppending dataframes...\n", dataFrame1

Output

This will produce the following output

DataFrame1 ...
      Car
0     BMW
1   Lexus
2    Audi
3  Jaguar
DataFrame1 length = 4

DataFrame2 ...
      Car
0  Mercedes
1     Tesla
2   Bentley
3   Mustang
DataFrame2 length = 4

Appending dataframes...
        Car
0       BMW
1     Lexus
2      Audi
3    Jaguar
0  Mercedes
1     Tesla
2   Bentley
3   Mustang

Updated on: 14-Sep-2021

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements