📜  如何连接两个或多个 Pandas DataFrames?

📅  最后修改于: 2022-05-13 01:55:52.332000             🧑  作者: Mango

如何连接两个或多个 Pandas DataFrames?

让我们了解如何连接两个或多个数据帧。可以使用 pandas.concat() 方法连接两个或多个数据帧。 pandas 中的 concat() 通过跨行或跨列组合数据帧来工作。我们可以沿行(轴 = 0)或沿列(轴 = 1)连接两个或多个数据框

第 1 步:导入 numpy 和 pandas 库。

Python3
import pandas as pd
import numpy as np


Python3
df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   index=["1", "2", "3", "4"],
                   columns=["A", "B", "C", "D"])
 
df2 = pd.DataFrame(np.random.randint(25, size=(6, 4)),
                   index=["5", "6", "7", "8", "9", "10"],
                   columns=["A", "B", "C", "D"])
 
df3 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   columns=["A", "B", "C", "D"])
 
df4 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   columns=["E", "F", "G", "H"])
 
display(df1, df2, df3, df4)


Python3
# concatenating df1 and df2 along rows
vertical_concat = pd.concat([df1, df2], axis=0)
 
# concatenating df3 and df4 along columns
horizontal_concat = pd.concat([df3, df4], axis=1)
 
display(vertical_concat, horizontal_concat)


第 2 步:创建两个数据帧,我们现在将把它们连接起来。为了创建数据框,我们将使用 numpy 和 pandas。

蟒蛇3

df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   index=["1", "2", "3", "4"],
                   columns=["A", "B", "C", "D"])
 
df2 = pd.DataFrame(np.random.randint(25, size=(6, 4)),
                   index=["5", "6", "7", "8", "9", "10"],
                   columns=["A", "B", "C", "D"])
 
df3 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   columns=["A", "B", "C", "D"])
 
df4 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   columns=["E", "F", "G", "H"])
 
display(df1, df2, df3, df4)

输出:

第 3 步:现在我们需要以列表的形式将两个数据框传递给 contact() 方法,并提及您要连接到哪个轴。

蟒蛇3

# concatenating df1 and df2 along rows
vertical_concat = pd.concat([df1, df2], axis=0)
 
# concatenating df3 and df4 along columns
horizontal_concat = pd.concat([df3, df4], axis=1)
 
display(vertical_concat, horizontal_concat)

输出: