按列名连接pandas数据帧

Ale*_*ont 59 python dataframe pandas

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

frame_1:
event_id, date, time, county_ID

frame_2:
countyid, state
Run Code Online (Sandbox Code Playgroud)

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

joined_dataframe
event_id, date, time, county, state
Run Code Online (Sandbox Code Playgroud)

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

Woo*_*ide 110

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

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
Run Code Online (Sandbox Code Playgroud)

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

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')
Run Code Online (Sandbox Code Playgroud)

  • 为了对此进行一点扩展,如果您想在一侧指定索引,可以使用“right_index=True”。 (3认同)

beh*_*uri 6

您需要county_ID为正确的框架创建索引:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )
Run Code Online (Sandbox Code Playgroud)

供您参考,在 pandas 中,当右框架在连接列上具有非唯一值时,左连接会中断。看到这个错误

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