[英]Pandas merge adding column
我有两个数据df1
和df2
。 df1
包含subject_id
和time
列,而df2
包含subject_id
和final_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.