pandas Appending to DataFrame Append a DataFrame to another DataFrame


Let us assume we have the following two DataFrames:

In [7]: df1
    A   B
0  a1  b1
1  a2  b2

In [8]: df2
    B   C
0  b1  c1

The two DataFrames are not required to have the same set of columns. The append method does not change either of the original DataFrames. Instead, it returns a new DataFrame by appending the original two. Appending a DataFrame to another one is quite simple:

In [9]: df1.append(df2)
     A   B    C
0   a1  b1  NaN
1   a2  b2  NaN
0  NaN  b1   c1

As you can see, it is possible to have duplicate indices (0 in this example). To avoid this issue, you may ask Pandas to reindex the new DataFrame for you:

In [10]: df1.append(df2, ignore_index = True)
     A   B    C
0   a1  b1  NaN
1   a2  b2  NaN
2  NaN  b1   c1