将一个数据帧中的列添加到另一个 python pandas

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33532216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:10:28  来源:igfitidea点击:

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

pythonpandas

提问by Jessica

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:

我一直在网上搜索并发现了类似的问题,但仍然找不到我正在寻找的答案。我有2个excel文件:

data1

数据1

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

data2

数据2

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

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

我想将列 F 从 data2 添加到 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 

采纳答案by Leb

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

回答by Nisarg Nikhil

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

回答by Nisarg Nikhil

import pandas as pd

f_column = data2["columnF"] 

data1 = pd.concat([data1,f_column], axis = 1) 

data1

will give the desired output.

将给出所需的输出。