简体   繁体   English

熊猫内部与Lambda加入

[英]Pandas Inner Join with Lambda

I have the following two frames: 我有以下两个框架:

frame1: 帧1:

            id
0  111-111-111
1  111-111-222
2  222-222-222
3  333-333-333

frame2: 式2:

     data       id
0    ones  111-111
1  threes  333-333

And, I have a lambda function that maps the frame1.id to frame2.id : 而且,我有一个lambda函数,将frame1.id映射到frame2.id

id_map = lambda x: x[:7]

My goal is to perform an inner join between these two tables, but to have the id go through the lambda. 我的目标是在这两个表之间执行内部联接,但要让ID通过lambda。 So that the output is: 这样的输出是:

            id    data
0  111-111-111    ones
1  111-111-222    ones
2  333-333-333  threes

I've come up with a rather non-elegant solution that almost does what I'm trying to do, however it messes up when the inner join removes rows: 我想出了一个非常优雅的解决方案, 几乎可以完成我想做的事情,但是当内部联接删除行时,它就变得混乱了:

# Save a copy the original ids of frame1
frame1_ids = frame1['id'].copy()
# Apply the id change to frame1
frame1['id'] = frame1['id'].apply(id_map)
# Merge
frame1 = frame1.merge(frame2, how='inner', on='id')
# Set the ids back to what they originally were
frame1['id'] = frame1_ids

Is there a elegant solution for this? 是否有一个优雅的解决方案?

Could use assign to create a dummy id column (newid) to join on like this: 可以使用assign创建一个虚拟id列(newid)进行连接,如下所示:

frame1.assign(newid=frame1['id'].str[:7])
      .merge(frame2, left_on='newid', right_on='id', suffixes=('','_y'))
      .drop(['id_y','newid'], axis=1)

Output: 输出:

            id    data
0  111-111-111    ones
1  111-111-222    ones
2  333-333-333  threes

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

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