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

馋奶兔 提交于 2019-12-06 18:30:16

问题


I have two pandas dataframes: df1 and df2.

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

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/25611220/pandas-lookup-mapping-one-column-in-a-dataframe-to-another-in-a-different-dataf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!