首页 > 解决方案 > 不确定如何根据条件合并数据

问题描述

df1:

tID  sID  dID  date1 date2
1234 4321 5432 7/12  8/13
7890 5688 4567 8/21  9/30

df2:

sID  dID  date3 
4321 5432 7/20
5688 4567 9/15 

我想将附加 a 分配tIDdf2if:

df3:

tID  sID  dID  date3 
1234 4321 5432 7/20
7890 5688 4567 9/15 

我的第一个想法是遍历数据框和使用if语句,但这似乎不是一种有效的方法。

任何帮助将非常感激。

标签: pythonpandasdataframemerge

解决方案


IIUC,首先将它们设置为相同的索引(如str,如果ID可能包含8/21编辑之前的ID。如果所有ID都是整数,则无需执行这些astype步骤)

df['sID'] = df.sID.astype(str)
df['dID'] = df.dID.astype(str)
df = df.set_index(['sID', 'dID'])


df2['sID'] = df2.sID.astype(str)
df2['dID'] = df2.dID.astype(str)
df2 = df2.set_index(['sID', 'dID'])

然后过滤并分配使用loc

m = df2.index.isin(df.index)
sub = df.loc[df2[m].date3.index]
s = df2[m].date3.between(sub.date1, sub.date2)
df2.loc[:, 'tID'] = df.loc[s[s].index, 'tID']

输出

                date3   tID
sID dID     
4321    5432    7/20    1234
5688    4567    9/15    7890

推荐阅读