
Hi, I’m Higashi.
Here’s how to concatenate two pandas DataFrames, either by stacking their rows or placing their columns side by side.

Let’s get started!
Concatenate DataFrames vertically
Use pandas.concat() to stack the rows:
Here, df1 and df2 are the two DataFrames you want to concatenate.
Use axis=0 to concatenate along the row axis.
Example: stack two DataFrames
I use these two CSV files in the example.

The two DataFrames start with different column names.
The first has [A, B, C], and the second has [D, E, F].
For this example, I want the stacked rows to share the first DataFrame’s column names.
The line df2.columns=df1.columns assigns those names to the second DataFrame.
After concatenation, the rows still have their original index labels.
Use df_concat=df_concat.reset_index(drop=True) to assign a fresh sequential index.
Here’s the full example.
import pandas as pd
#Load Dataframes
data1='data1.csv'
data2='data2.csv'
df1=pd.read_csv(data1)
df2=pd.read_csv(data2)
#Print Original Dataframes
print('df1=')
print(df1)
print('df2=')
print(df2)
#Unify Header
df2.columns=df1.columns
#Concatenate Process
df_concat=pd.concat([df1,df2],axis=0)
#Reset Row Number
df_concat=df_concat.reset_index(drop=True)
#Print Concatenate Dataframes
print('df_concat=')
print(df_concat)
Here’s the result.

Concatenate DataFrames horizontally
Use the same function to put the columns side by side:
Here, df1 and df2 are the two DataFrames you want to concatenate.
Use axis=1 to concatenate along the column axis.
Example: concatenate columns
I’ll use the same CSV files.

In this example, the two DataFrames already have matching row indexes. pandas aligns the rows by index and keeps the original column names.
Leave out df2.columns=df1.columns from the previous example.
That line would rename the second DataFrame’s columns.
Here’s the full example.
import pandas as pd
#Load Dataframes
data1='data1.csv'
data2='data2.csv'
df1=pd.read_csv(data1)
df2=pd.read_csv(data2)
#Print Original Dataframes
print('df1=')
print(df1)
print('df2=')
print(df2)
#Concatenate Process
df_concat=pd.concat([df1,df2],axis=1)
#Print Concatenate Dataframes
print('df_concat=')
print(df_concat)
Here’s the result.

Thanks for reading!


コメント