Pandas Tutorial Pandas References

Pandas DataFrame - append() function



The Pandas DataFrame append() function appends rows of other to the end of caller and returns the resulting new object. The columns in other that are not in the caller are added as new columns.

Syntax

DataFrame.append(other, ignore_index=False, 
                 verify_integrity=False, 
                 sort=False)

Parameters

other Required. Specify data to append as another DataFrame or Series/dict-like object, or list of these.
ignore_index Optional. If set to True, the resulting axis will be labeled 0, 1, …, n - 1. Default: False.
verify_integrity Optional. If set to True, raise ValueError on creating index with duplicates. Default: False.
sort Optional. If set to True, sort columns if the columns of self and other are not aligned. Default: False.

Return Value

Returns a new DataFrame consisting of the rows of caller and the rows of other.

Example: append() example

In the example below, the append() function is used to append the rows of a given DataFrame to the end of another DataFrame.

import pandas as pd
import numpy as np

df1 = pd.DataFrame({
  "x": [1, 2, 3],
  "y": [10, 20, 30]
})

df2 = pd.DataFrame({
  "x": [1, 1, 2],
  "y": [10, 15, 25]
})

print("df1 contains:")
print(df1,"\n")

print("df2 contains:")
print(df2,"\n")

print("df1.append(df2) returns:")
print(df1.append(df2),"\n")

print("df1.append(df2, ignore_index=True) returns:")
print(df1.append(df2, ignore_index=True),"\n")

The output of the above code will be:

df1 contains:
   x   y
0  1  10
1  2  20
2  3  30 

df2 contains:
   x   y
0  1  10
1  1  15
2  2  25 

df1.append(df2) returns:
   x   y
0  1  10
1  2  20
2  3  30
0  1  10
1  1  15
2  2  25 

df1.append(df2, ignore_index=True) returns:
   x   y
0  1  10
1  2  20
2  3  30
3  1  10
4  1  15
5  2  25 

Example: When columns are different

The columns in other that are not in the caller are added as new columns. Consider the example below:

import pandas as pd
import numpy as np

df1 = pd.DataFrame({
  "x": [1, 2, 3],
  "y": [10, 20, 30]
})

df2 = pd.DataFrame({
  "x": [1, 1, 2],
  "y": [10, 15, 25],
  "z": [100, 200, 300]
})

print("df1 contains:")
print(df1,"\n")

print("df2 contains:")
print(df2,"\n")

print("df1.append(df2) returns:")
print(df1.append(df2),"\n")

The output of the above code will be:

df1 contains:
   x   y
0  1  10
1  2  20
2  3  30 

df2 contains:
   x   y    z
0  1  10  100
1  1  15  200
2  2  25  300 

df1.append(df2) returns:
   x   y      z
0  1  10    NaN
1  2  20    NaN
2  3  30    NaN
0  1  10  100.0
1  1  15  200.0
2  2  25  300.0 

❮ Pandas DataFrame - Functions