Python - 如何沿行连接两个或更多熊猫数据框?
要连接两个以上的熊猫数据框,请使用 concat() 方法。将axis 参数设置为axis = 0 以沿行连接。首先,导入所需的库−
import pandas as pd
让我们创建一个第 1 个数据框 −
dataFrame1 = pd.DataFrame( { "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90], }, index=[0, 1, 2], )
让我们创建一个第 2 个数据框 −
dataFrame2 = pd.DataFrame( { "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180], }, index=[3, 4, 5], )
让我们创建一个第 3 个数据框 −
dataFrame3 = pd.DataFrame( { "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280], }, index=[6, 7, 8], )
使用 concat() 连接所有 3 个数据框。将 "axis=1" 设置为沿行连接 −
res = [dataFrame1, dataFrame2, dataFrame3] pd.concat(res, axis=1))
示例
以下是代码 −
import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90], }, index=[0, 1, 2], ) # DataFrame1 print"DataFrame1...\n",dataFrame1 # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180], }, index=[3, 4, 5], ) # DataFrame2 print"DataFrame2...\n",dataFrame2 dataFrame3 = pd.DataFrame( { "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280], }, index=[6, 7, 8], ) # DataFrame3 print"DataFrame3...\n",dataFrame3 # concatenating more than 2 dataframes # set "axis=0" for concatenation along rows res = [dataFrame1, dataFrame2, dataFrame3] print"\n Concatenating all the 3 DataFrames (along rows)...\n", pd.concat(res, axis=0)
输出
这将产生以下输出 −
DataFrame1... Col1 Col2 Col3 0 10 40 70 1 20 50 80 2 30 60 90 DataFrame2... Col1 Col2 Col3 3 100 130 160 4 110 140 170 5 120 150 180 DataFrame3... Col1 Col2 Col3 6 200 230 260 7 210 240 270 8 220 250 280 Concatenating all the 3 DataFrames (along rows)... Col1 Col2 Col3 0 10 40 70 1 20 50 80 2 30 60 90 3 100 130 160 4 110 140 170 5 120 150 180 6 200 230 260 7 210 240 270 8 220 250 280
广告