所以如何通过2个条件(id和month)将这些值从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'])
似乎在您的代码的这一部分:
# 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'])
您不应该使用广告组,应该使用“月/日期”列执行联接,因为日期是数据中每个事件唯一的部分。