首页 > 解决方案 > 如何根据日期时间约束从另一个数据框中提取行?

问题描述

基本上我试图回答这个问题:“客户从 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 

标签: python-3.xpandasnumpydataframejupyter-notebook

解决方案


首先,我们需要在df1df2检索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_atagent_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 日

推荐阅读