rbind & cbind Two pandas DataFrames in Python (2 Examples)

In this article, I’ll demonstrate how to row- and column-bind two pandas DataFrames in Python.

Example 1: Cbind Two pandas DataFrames in Python

import pandas as pd                             # Load pandas
df_h1 = pd.DataFrame({"ID":range(10, 15),       # Construct pandas DataFrames
                      "A":range(100, 105),
                      "B":range(200, 205)})
print(df_h1)
#    ID    A    B
# 0  10  100  200
# 1  11  101  201
# 2  12  102  202
# 3  13  103  203
# 4  14  104  204
df_h2 = pd.DataFrame({"ID":range(13, 17),
                      "C":range(35, 31, - 1),
                      "D":range(45, 41, - 1)})
print(df_h2)
#    ID   C   D
# 0  13  35  45
# 1  14  34  44
# 2  15  33  43
# 3  16  32  42
df_h_all = pd.merge(df_h1, df_h2, on = "ID")    # Append horizontally
print(df_h_all)
#    ID    A    B   C   D
# 0  13  103  203  35  45
# 1  14  104  204  34  44

Example 2: Rbind Two pandas DataFrames in Python

df_v1 = pd.DataFrame({"A":range(1, 5),          # Construct pandas DataFrames
                      "B":range(16, 20)})
print(df_v1)
#    A   B
# 0  1  16
# 1  2  17
# 2  3  18
# 3  4  19
df_v2 = pd.DataFrame({"A":range(301, 305),
                      "B":range(401, 405)})
print(df_v2)
#      A    B
# 0  301  401
# 1  302  402
# 2  303  403
# 3  304  404
df_v_all = pd.concat([df_v1, df_v2])            # Append vertically
print(df_v_all)
#      A    B
# 0    1   16
# 1    2   17
# 2    3   18
# 3    4   19
# 0  301  401
# 1  302  402
# 2  303  403
# 3  304  404

Further Resources

You may have a look at the following Python programming tutorials. They discuss topics such as variables, numeric values, and character strings:

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