首页 > 解决方案 > 存在重复项时如何使用 2 个条件映射值

问题描述

如何根据 2 个条件(月份和 id)进行成本归属。

问题是.. id 每个月都会重复,但是每个月的成本都不同

那么如何通过 2 个条件(id 和月份)将这些值从 reff 表映射到主数据框

总体上有重复,但在某个月份没有重复。

我的数据样本

cw=

  adgroup    Date    
  1001   2018-08-01
  1001   2019-03-01
  1003   2018-03-01
  1002   2018-03-01
  1001   2018-05-01
  1003   2018-08-01
  1001   2019-12-12
  1002   2019-03-01
  1001   2019-08-01

参考表

f_spend=


    adgroup   Month        cost  

    1001    2019/08     101,1
    1002    2019/08      70,1
    1003    2019/03    4221,1
    1001    2018/05     101,1
    1002    2018/03      50,1
    1003    2018/08    8221,1
    1001    2019/08    5401,1
    1002    2019/08      50,1
    1003    2019/12    9221,1
    1001    2019/08     101,1
    1002    2019/08      50,1
    1003    2019/12    6221,1

我做了什么

# grouping by the main data( facebook data) by id

cw["id"].replace(to_replace=[None], value=np.nan, inplace=True)

grouped_cw = cw.groupby(["adgroup"]).sum()
grouped_cw = pd.DataFrame(grouped_cw)



# merging two tables together

f_spend = f_spend.merge(grouped_cw, left_on='adgroup', right_index=True)
f_spend["cost"] = pd.to_numeric(f_spend["cost"])



# mapping values to original data
cw['spent'] = cw['adgroup'].map(f_spend.set_index('adgroup')['cost'])


不起作用,因为我有重复,但我不应该放弃它们

标签: pythonpandasnumpyconcat

解决方案


这部分代码似乎是:

# merging two tables together
f_spend = f_spend.merge(grouped_cw, left_on='adgroup', right_index=True)
f_spend["cost"] = pd.to_numeric(f_spend["cost"])

# mapping values to original data
cw['spent'] = cw['adgroup'].map(f_spend.set_index('adgroup')['cost'])

你不应该使用广告组,你应该使用你的月份/日期列来执行连接,因为日期是你的数据的一部分,对于每个事件都是唯一的。


推荐阅读