Combine Two pandas DataFrames in Python – Append & Concatenate (Example Code)

This tutorial shows how to stack two pandas DataFrames in the Python programming language.

Preparing the Example

import pandas as pd                                # Import pandas library to Python
my_df1 = pd.DataFrame({"A":["foo", "bar", "foo"],  # Construct two pandas DataFrames
                     "B":range(1, 4),
                     "C":["a", "b", "c"]})
print(my_df1)
#      A  B  C
# 0  foo  1  a
# 1  bar  2  b
# 2  foo  3  c
my_df2 = pd.DataFrame({"A":["x", "x", "x"],
                     "B":range(10, 7, - 1),
                     "C":["y", "y", "y"]})
print(my_df2)
#    A   B  C
# 0  x  10  y
# 1  x   9  y
# 2  x   8  y

Example: Appending Two pandas DataFrames

my_df_combined = my_df1.append(my_df2)             # Stack two DataFrames
print(my_df_combined)                              # Display concatenated DataFrames
#      A   B  C
# 0  foo   1  a
# 1  bar   2  b
# 2  foo   3  c
# 0    x  10  y
# 1    x   9  y
# 2    x   8  y

Further Resources & Related Tutorials

In addition, you may want to read the other articles on my website.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top