Append pandas DataFrames Vertically & Horizontally in Python (2 Examples)

In this Python tutorial you’ll learn how to merge pandas DataFrames vertically and horizontally.

Example 1: Merging Two pandas DataFrames Vertically

import pandas as pd                             # Load pandas library
df_v1 = pd.DataFrame({"A":range(11, 15),        # Construct pandas DataFrames
                      "B":range(21, 25)})
print(df_v1)
#     A   B
# 0  11  21
# 1  12  22
# 2  13  23
# 3  14  24
df_v2 = pd.DataFrame({"A":range(31, 35),
                      "B":range(41, 45)})
print(df_v2)
#     A   B
# 0  31  41
# 1  32  42
# 2  33  43
# 3  34  44
df_v_all = pd.concat([df_v1, df_v2])            # Append vertically
print(df_v_all)
#     A   B
# 0  11  21
# 1  12  22
# 2  13  23
# 3  14  24
# 0  31  41
# 1  32  42
# 2  33  43
# 3  34  44

Example 2: Merging Two pandas DataFrames Horizontally

df_h1 = pd.DataFrame({"ID":range(1, 5),         # Construct pandas DataFrames
                      "A":range(11, 15),
                      "B":range(21, 25)})
print(df_h1)
#    ID   A   B
# 0   1  11  21
# 1   2  12  22
# 2   3  13  23
# 3   4  14  24
df_h2 = pd.DataFrame({"ID":range(3, 7),
                      "C":range(31, 35),
                      "D":range(41, 45)})
print(df_h2)
#    ID   C   D
# 0   3  31  41
# 1   4  32  42
# 2   5  33  43
# 3   6  34  44
df_h_all = pd.merge(df_h1, df_h2, on = "ID")    # Append horizontally
print(df_h_all)
#    ID   A   B   C   D
# 0   3  13  23  31  41
# 1   4  14  24  32  42

Leave a Reply

Your email address will not be published. Required fields are marked *

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