pandas 查找,将数据框中的一列映射到另一数据框中的另一列

问题描述:

我有两个熊猫数据帧:df1和df2.

I have two pandas dataframes: df1 and df2.

df1具有X和Y列以及weeknum. df2具有Z列,weeknum和datetime.

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

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

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

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

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

您可以使用合并语法获取想要的列

You can grab the columns you want in the merge syntax

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

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

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.