python-3.x - 如何根据日期时间约束从另一个数据框中提取行?
问题描述
基本上我试图回答这个问题:“客户从 X 日期起最近的 4 个订单是什么......”但问题是我试图对按电子邮件日志排序的表中的每一行执行此操作,并且一个独特的日期。
所以我必须查看这些电子邮件日志 (df1) 中的每个日期,找出 df1 中的 agent_id 是否与 agent_id df2(订单历史记录)匹配,然后从 df2 中提取最近的 4 个订单。IE:客户端 123 在 3 月 3 日(df1)收到一封电子邮件......然后我需要在 df2 中提取客户端 123 的 4 个最新条目,这些条目等于或小于日期(3 月 3 日)。
我想出了这个凌乱的功能,但是在循环超过 1000 行时它并不实用……有什么想法可以扩大规模吗?
谢谢,
df1 = pd.DataFrame({'unique_col': ['a', 'b', 'c', 'd'], 'agent_id': [1, 2, 3, 4], 'created_at_email': ['1/5/2020', '1/6/2020', '1/8/2020', '1/8/2020']})
df2 = pd.DataFrame({'unique_col': ['a', 'b', 'c', 'd'], 'agent_id': [1, 1, 3, 1], 'created_at': ['1/4/2020', '1/5/2020', '1/6/2020', '1/9/2020']})
# note: super not optimized at all...
def function():
for index, row in df1.iterrows():
for index, row2 in df2.iterrows():
if row['agent_id'] == row2['agent_id']:
if row2['created_at'] <= row['created_at_email']:
print( 1, row2['created_at'], row['created_at_email'], row2['agent_id'], row['agent_id'], row['unique_col'], row2['unique_col'])
else:
print( 0, row2['created_at'], row['created_at_email'], row2['agent_id'], row['agent_id'], row['unique_col'], row2['unique_col'])
#else:
#print( 0, row2['created_at'], row['created_at_email'], row2['agent_id'], row['agent_id'])
function()
output:
1 1/4/2020 1/5/2020 1 1 a a
1 1/5/2020 1/5/2020 1 1 a b
0 1/9/2020 1/5/2020 1 1 a d
1 1/6/2020 1/8/2020 3 3 c c
解决方案
首先,我们需要在df1
和df2
检索created_at_email
为此,您可以将两个数据帧索引设置为agent_id
列,之后我们可以连接两个数据帧
df1.index = df1.agent_id
df2.index = df2.agent_id
result = df2.join(df1,lsuffix='_df2')
join
方法匹配基于索引的相等性。
我们将重置索引result
以防止在 期间出现错误groupby
并删除不必要的列
result.reset_index(drop=True,inplace=True)
result.drop(['agent_id_df2'],axis=1,inplace=True)
为了维护每个订单的最新订单,我们将对数据框进行agent_id
排序created_at
agent_id
result.sort_values(['agent_id','created_at'],inplace=True)
之后,您可以groupby
使用该head
方法检索每个代理的 4 个最近订单
result = result.groupby('agent_id').head(4)
最后结果
unique_col_df2 | created_at | unique_col | agent_id | created_at_email | |
---|---|---|---|---|---|
0 | 一个 | 2020 年 1 月 4 日 | 一个 | 1 | 2020 年 1 月 5 日 |
1 | b | 2020 年 1 月 5 日 | 一个 | 1 | 2020 年 1 月 5 日 |
2 | d | 2020 年 1 月 9 日 | 一个 | 1 | 2020 年 1 月 5 日 |
3 | C | 2020 年 1 月 6 日 | C | 3 | 2020 年 1 月 8 日 |
推荐阅读
- ios - webkit 不为不透明度设置动画
- python - 在 pyqt5 界面中动态更新 matplotlib 画布
- python - Plotly Python 中的刻度格式
- python - 如何使用 Python 从 ZIP 文件中查找字符串
- javascript - 模仿 TypeScript 中的扩展方法
- css - 为什么我的 CSS Grid 不能在 IE 11 中正确呈现?
- node.js - 在 docker 中运行 ng build 时如何为 node.js 分配更多内存?
- python - 在 Python 中,根据该数组的特定列中的值将数组行分成组
- sql-server - 如何根据其他行插入行?
- excel - Excel - 条件格式:如果上面的单元格不同,请更改填充颜色