Python Pandas:在具有不同名称的字段上加入 DataFrames?

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

Pandas: join DataFrames on field with different names?

pythonpandasjoindataframefield

提问by woshitom

According to this documentationI can only make a join between fields having the same name.

根据此文档,我只能在具有相同名称的字段之间进行连接。

Do you know if it's possible to join two DataFrames on a field having different names?

您知道是否可以在具有不同名称的字段上连接两个 DataFrame 吗?

The equivalent in SQL would be:

SQL 中的等效项是:

SELECT *
FROM df1
LEFT OUTER JOIN df2
  ON df1.id_key = df2.fk_key

采纳答案by Alex Riley

I think what you want is possible using merge. Pass in the keyword arguments for left_onand right_onto tell Pandas which column(s) from each DataFrame to use as keys:

我认为使用merge. 传入left_on和的关键字参数right_on以告诉 Pandas 将每个 DataFrame 中的哪些列用作键:

pandas.merge(df1, df2, how='left', left_on=['id_key'], right_on=['fk_key'])

The documentation describes this in more detail on this page.

该文档在此页面上更详细地描述了这一点

回答by Vipul Saxena

df2['id_key'] = df2['fk_key'].str.lower()

df2['id_key'] = df2['fk_key'].str.lower()

df1['id_key'] = df1['id_key'].str.lower()

df1['id_key'] = df1['id_key'].str.lower()

Now try to merge the dataframes

现在尝试合并数据帧

df3 = pd.merge(df2,df1,how='inner', on='id_key')

df3 = pd.merge(df2,df1,how='inner', on='id_key')