繁体   English   中英

熊猫合并添加列

[英]Pandas merge adding column

我有两个数据df1df2 df1包含subject_idtime列,而df2包含subject_idfinal_time列。 我想要做的是为df1每个subject_id添加一列,其中final_time来自df2 final_time ,但仅来自df1包含的subject_ids 我已经尝试过df1.merge(df2,how='left')但仍然从df2获取所有subject_id ,而df2则更长,并且包含许多'subject_id'的副本。

我要寻找的示例:

df1


    subject_id  time  

 0          15  12:00 
 1          20  12:05 
 2          21  12:10
 3          25  12:00 

df2


    subject_id  final_time 

 0          15       12:30      
 1          15       12:30      
 2          15       12:30      
 3          20       12:45      
 4          20       12:45      
 5          21       12:50      
 6          25        1:00       
 7          25        1:00       
 8          25        1:00      

我在寻找什么

    subject_id  time  final_time 

 0          15  12:00      12:30      
 1          20  12:05      12:45      
 2          21  12:10      12:50      
 3          25  12:00       1:00       

你应该用

df1.merge(df2, on='subject_id')

默认how是“内部”,它将仅与两列中的那些条目匹配。 on告诉合并仅在您感兴趣的列上匹配

为我工作。 df1没有的结果

df1 = pd.DataFrame(dict(subject_id=[1, 2, 3], time=[9, 8, 7]))
df2 = pd.DataFrame(dict(subject_id=[2, 2, 4], final_time=[6, 5, 4]))

df1.merge(df2, 'left')

   subject_id  time  final_time
0           1     9         NaN
1           2     8         6.0
2           2     8         5.0
3           3     7         NaN

暂无
暂无

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

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