【问题标题】:pandas calculated field by comparing other fields and dictionary valuespandas 通过比较其他字段和字典值来计算字段
【发布时间】:2020-02-20 14:02:25
【问题描述】:

我有两个数据框。第一个看起来像这样:

id, orderdate, orderid, amount,camp1, camp2, camp3
1   2020-01-01  100      100       1    0       0
2   2020-02-01  120      200       1    0       1
3   2019-12-01  130      500       0    1       0
4   2019-11-01  150      750       0    1       0
5   2020-01-01  160      1000      1    1       1

camp1, camp2, camp3 部分显示客户是否参加了活动。

并且广告系列有一个时期字典,这样

camp_periods = {'camp1': 
                        [datetime.strptime('2019-04-08', '%Y-%m-%d'), datetime.strptime('2019-06-06', '%Y-%m-%d')],
                'camp2':
                        [datetime.strptime('2019-09-15', '%Y-%m-%d'), datetime.strptime('2019-09-28', '%Y-%m-%d')],
                'camp3':
                        [datetime.strptime('2019-11-15', '%Y-%m-%d'), datetime.strptime('2019-12-28', '%Y-%m-%d')]
                 }

如果orderdatecamp_periods 字典中的活动期间之间,并且如果客户参加了该活动,我想创建一个表格,给出每个客户的订单数量和order amounts 总数。

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    我不确定我是否很好地理解了你的问题,我猜当你说order amounts 的订单数和总数时,你想得到第一个n 小于或等于 a 的订单数给定总数order amounts,这是我的方法:

    数据示例:

    from operator import or_
    from functools import reduce
    
    
    number_orders = 2
    total_order_amounts = 3000
    

    orderdate 在 camp_periods 的活动期间之间 字典以及客户是否参加了该活动

    cond = [(df[k].astype('bool') & df['orderdate'].between(*v)) for k, v in camp_periods.items()]
    cond = reduce(or_, cond)
    df_cond = df[cond]
    df_final = df_cond[df_cond['amount'].cumsum() <= total_order_amounts].head(number_orders)
    
    df_final
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多