我有两个数据帧df1
和df2
。df1
包含列subject_id
和time
列,df2
包含列subject_id
和final_time
列。我想做的是为每个df1
subject_id
添加一列,其中包含来自df2
的final_time
,但仅来自df1
中包含的subject_ids
。我已经尝试了df1.merge(df2,how='left')
但仍然从df2
中获取所有subject_id
,它更长并且包含许多重复的"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
的默认值为 inner,它仅匹配两列中的条目。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