python - 不确定如何根据条件合并数据
问题描述
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 分配tID
给df2
if:
date3
介于date1
和之间date2
- 是
sID
一样的 - 是
dID
一样的
df3:
tID sID dID date3
1234 4321 5432 7/20
7890 5688 4567 9/15
我的第一个想法是遍历数据框和使用if
语句,但这似乎不是一种有效的方法。
任何帮助将非常感激。
解决方案
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
推荐阅读
- python - 如何使用 curses 和 Python 设置窗口背景颜色?
- mongodb - ServerSelectionTimeoutError:通过 pymongo 连接到 Atlas 时出现超时错误
- java - Mysql Get_Lock 和 Release_Lock 函数耗时较长
- php - 获取当前时间,将其设置为不更新的变量
- java - 如何使用放心验证带有特殊字符的响应正文?
- jquery - Laravel 中基于 Ajax 的自动完成功能太慢
- python - 如何为我的 Dash 应用程序正确添加样式?
- .net - 单元测试 web api
- python - 将 auth_views.login 从 django 1 转换为 2
- arrays - 试图删除数组中的 _id。它似乎不起作用