繁体   English   中英

按列名连接pandas数据帧

[英]Joining pandas dataframes by column names

我有两个具有以下列名称的数据帧:

frame_1:
event_id, date, time, county_ID

frame_2:
countyid, state

我想通过在county_ID = countyid上加入(左)获得包含以下列的数据county_ID = countyid

joined_dataframe
event_id, date, time, county, state

如果我想要加入的列不是索引,我无法弄清楚如何做到这一点。 什么是最简单的方法? 谢谢!

您可以使用left_on和right_on选项,如下所示:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

如果密钥位于左侧数据框中,我不确定是否只想合并。 如果是这种情况,那么以下将会这样做(以上将实际上做多对多合并)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

你需要将county_ID作为右框架的索引:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

为了您的信息,在pandas中,当右框架在连接列上具有非唯一值时,连接会中断。 看到这个bug

所以你需要在加入之前验证完整性, verify_integrity=True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM