tony selcuk
tony selcuk

Reputation: 687

Combining csv files columns together Pandas Python

I am trying to combine file1-3.csv so that I could get the expected result. I want to combine all the rows together on all 3 file, but disregard the 1st column as it is the same on all 3 files. How can i do this with pandas.

Code:

import pandas as pd 

file1 = pd.read_csv('STDOutputs_Q1.csv')
file2 = pd.read_csv('STDOutputs_Q2.csv')
file3 = pd.read_csv('STDOutputs_Q3.csv')

Inside file1.csv

element,LNPT,SNPT
[ 2.  2. 30.],89,60
[ 2.  2. 40.],999,77

Inside file2.csv

element,MxU,MxD,TT
[ 2.  2. 30.],17127,-3,0
[ 2.  2. 40.],17141,-40,2

Inside file3.csv

element,TNT
[ 2.  2. 30.],1000
[ 2.  2. 40.],30

Expected Results:

element,LNPT,SNPT,MxU,MxD,TT,TNT
[ 2.  2. 30.],89,60,17127,-3,0,1000
[ 2.  2. 40.],999,77,17141,-40,2,30

Upvotes: 1

Views: 171

Answers (1)

Tiger
Tiger

Reputation: 13

You can use pd.join like:

q1_2 = file1.join(file2, lsuffix='_Q1', rsuffix='_Q2')
file1-3 = q1_2.join(file3,  rsuffix='_Q3')

Or if the 'element' column is the same for all three data frame, and there are no conflicting column names, you can use pd.merge:

q1_2 = file1.merge(file2)
file1-3 = q1_2.merge(file3)

Upvotes: 1

Related Questions