Pandas 查找,将数据框中的一列映射到不同数据框中的另一列

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

Pandas lookup, mapping one column in a dataframe to another in a different dataframe

pythondatabasepandaslookup

提问by wolfsatthedoor

I have two pandas dataframes: df1 and df2.

我有两个Pandas数据框:df1 和 df2。

df1 has columns X and Y and weeknum. df2 has columns Z, weeknum, and datetime.

df1 有 X 列和 Y 列以及weeknum。df2 有 Z、weeknum 和 datetime 列。

I want to basically keep df1 and have an extra column in it that is corresponding datetime for weeknum.

我想基本上保留 df1 并在其中有一个额外的列,该列对应于weeknum的日期时间。

I can use merge but there must be a cleaner way, without having to drop column Z.

我可以使用合并,但必须有一种更简洁的方法,而不必删除 Z 列。

回答by Mike

You can grab the columns you want in the merge syntax

您可以在合并语法中抓取所需的列

df1 = df1.merge(df2[['weeknum', 'datetime']], on=['weeknum'])

This will make sure you don't have any unwanted columns of df2 in your result, but you don't have to delete those columns from your second DataFrame in the process.

这将确保您的结果中没有任何不需要的 df2 列,但您不必在此过程中从第二个 DataFrame 中删除这些列。