如何根据pandas python中的特定列合并两个数据框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37697195/
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-08-19 19:48:55  来源:igfitidea点击:

how to merge two data frames based on particular column in pandas python?

pythonpython-2.7pandas

提问by Sai Rajesh

I have to merge two dataframes:

我必须合并两个数据框:

df1

df1

company,standard
tata,A1
cts,A2
dell,A3

df2

df2

company,return
tata,71
dell,78
cts,27
hcl,23

I have to unify both dataframes to one dataframe. I need output like:

我必须将两个数据帧统一为一个数据帧。我需要这样的输出:

company,standard,return
tata,A1,71
cts,A2,27
dell,A3,78

回答by jezrael

Use merge:

使用merge

print (pd.merge(df1, df2, on='company'))

Sample:

样本:

print (df1)
  company standard
0    tata       A1
1     cts       A2
2    dell       A3

print (df2)
  company  return
0    tata      71
1    dell      78
2     cts      27
3     hcl      23

print (pd.merge(df1, df2, on='company'))
  company standard  return
0    tata       A1      71
1     cts       A2      27
2    dell       A3      78

回答by Good Will

In order to successfully merge two data frames based on common column(s), the dtype for common column(s) in both data frames must be the same! dtype for a column can be changed by:

为了基于公共列成功合并两个数据框,两个数据框中公共列的 dtype 必须相同!列的 dtype 可以通过以下方式更改:

df['commonCol'] = df['commonCol'].astype(int)