“Python” How to Concatenate Two Pandas-Dataframes. Demonstrated Vertically and Horizontally.

Python
higashi
higashi

Hi, I’m higashi.

 

In this page, I introduce how to concatenate two pandas’s dataframes as shown below.

summary of this page

OK, let’s get started!!

 

Sponsored Links

How to Concatenate Dataframes Vertically

How to concatenate two dataframes vertically is shown below.

concatenate_dataframe=pandas.concat([df1,df2],axis=1)
※df1, df2 : two data frames you want to concatenate

The “axis=1” at end means vertically.

 

Sponsored Links

Sample Code of Concatenate dataframes Vertically

These two csv file is used for sample code.

sample csv data for demonstration

These two dataframes has different header as you can confirm above.

(data1 has [A, B, C] and data2 has [D, E, F])

 

You should choose which header remain.

In below code, by conducted df2.columns=df1.columns, df1’s header is remain.

 

And these dataframes maintain original row number after concatenate too.

So we should reset row number by conducted df_concat=df_concat.reset_index(drop=True).

 

The overall code is below.

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)

Result of this code is below.

Result of sample code

I think it is no problem.

 

Sponsored Links

How to Concatenate Dataframes Horizontally

How to concatenate two dataframes horizontally is shown below.

concatenate_dataframe=pandas.concat([df1,df2],axis=1)
※df1, df2 : two data frames you want to concatenate

The “axis=1” at end means horizontally.

 

Sponsored Links

How to Concatenate Dataframes Horizontally

Same csv data is used too.

sample csv data for demonstration

In this pattern, since concatenate dataframe will have original header and row number, there is no careful point.

*Please delete df2.columns=df1.columnsfrom previous code.

Otherwise header name will be wrong.

 

The overall code is below.

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=0)
#Print Concatenate Dataframes
print('df_concat=')
print(df_concat)

Result of this code is below.

Result of sample code

This is no problem too.

 

That’s all. Thank you!!

コメント

Copied title and URL