Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding column(s) from one dataframe to another python pandas

Tags:

python

pandas

I have been searching online and found similar questions but still couldn't find the answer to what I'm looking for. I have 2 excel files:

data1

ColumnA    columnB    columnC   columnD
  A          B          C          D
  A          B          C          D
  A          B          C          D

data2

ColumnE    columnF    columnG   
  E          F          G          
  E          F          G          
  E          F          G    

I want to add the column F from data2 to data1:

ColumnA    columnB    columnC   columnD  columnF 
  A          B          C          D       F
  A          B          C          D       F
  A          B          C          D       F

I tried

data2['columnF'] = data1['columnF']  #doesn't work

also tried

data1['columnF'] = ''   #adding a columnF to data1
merg_left = pd.merge(left=data1,right=data2, how='left',      
left_on='columnF', right_on='columnF')  
#gave me a weird output file 
like image 349
Jessica Avatar asked Nov 04 '15 21:11

Jessica


2 Answers

import pandas as pd
import io

data = """
ColumnA    columnB    columnC   columnD
  A          B          C          D
  A          B          C          D
  A          B          C          D
    """
data1 = """
ColumnE    columnF    columnG
  E          F          G
  E          F          G
  E          F          G
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')
df1 = pd.read_csv(io.StringIO(data1), delimiter='\s+')

df['columnF'] = pd.Series(df1['columnF'])

print(df)

Will give you:

  ColumnA columnB columnC columnD columnF
0       A       B       C       D       F
1       A       B       C       D       F
2       A       B       C       D       F
like image 199
Leb Avatar answered Oct 07 '22 19:10

Leb


import pandas as pd
f_column = data2["columnF"]
data1 = pd.concat([data1,f_column], axis = 1)
data1
     columnA      columnB     columnC     columnF
0       a            b            c         f
1       a            b            c         f
2       a            b            c         f
like image 34
Nisarg Nikhil Avatar answered Oct 07 '22 19:10

Nisarg Nikhil