如何按营销活动分组并创建对应命名的产品价格列?
问题:按指定产品顺序生成对应价格列
需要从现有列Product Price创建三个新列Product 1 Price、Product 2 Price、Product 3 Price,产品编号顺序必须严格匹配DataFrame中已有的Product 1、Product 2、Product 3列的值,且价格要对应具体营销活动的定价。
当前DataFrame
import pandas as pd import numpy as np df = pd.DataFrame(columns=['Product Name','Product Price','Campaign Name','Campaign Start Date','Product 1','Product 2','Product 3']) df.loc[0] = ['Apples',5,'Summer','2023-06-01','Mangos','Apples','Bananas'] df.loc[1] = ['Mangos',15,'Summer','2023-06-01','Mangos','Apples','Bananas'] df.loc[2] = ['Bananas',10,'Summer','2023-06-01','Mangos','Apples','Bananas'] df.loc[3] = ['Guava',9,'Fall','2023-10-01','Guava','Apples',np.nan] df.loc[4] = ['Apples',7,'Fall','2023-10-01','Guava','Apples',np.nan]
对应的表格:
| Product Name | Product Price | Campaign Name | Campaign Start Date | Product 1 | Product 2 | Product 3 |
|---|---|---|---|---|---|---|
| Apples | 5 | Summer | 2023-06-01 | Mangos | Apples | Bananas |
| Mangos | 15 | Summer | 2023-06-01 | Mangos | Apples | Bananas |
| Bananas | 10 | Summer | 2023-06-01 | Mangos | Apples | Bananas |
| Guava | 9 | Fall | 2023-10-01 | Guava | Apples | NaN |
| Apples | 7 | Fall | 2023-10-01 | Guava | Apples | NaN |
目标DataFrame
最终需要得到按活动聚合、并匹配产品顺序的价格列:
df2 = pd.DataFrame(columns=['Campaign Name','Campaign Start Date','Product 1','Product 2','Product 3','Product 1 Price','Product 2 Price','Product 3 Price']) df2.loc[0] = ['Summer','2023-06-01','Mangos','Apples','Bananas',15,5,10] df2.loc[1] = ['Fall','2023-10-01','Guava','Apples',np.nan,9,7,np.nan]
对应的表格:
| Campaign Name | Campaign Start Date | Product 1 | Product 2 | Product 3 | Product 1 Price | Product 2 Price | Product 3 Price |
|---|---|---|---|---|---|---|---|
| Summer | 2023-06-01 | Mangos | Apples | Bananas | 15 | 5 | 10.0 |
| Fall | 2023-10-01 | Guava | Apples | NaN | 9 | 7 | NaN |
用户曾尝试使用透视表,但生成的列名不符合Product 1/2/3 Price的要求,需要调整实现方式。
解决方案
步骤1:构建按活动分组的产品-价格映射
先按Campaign Name分组,为每个活动创建产品名称到价格的字典:
price_maps = df.groupby('Campaign Name').apply( lambda x: dict(zip(x['Product Name'], x['Product Price'])) ).to_dict()
步骤2:提取每个活动的唯一产品配置
由于同一活动下的Product 1/2/3列值完全一致,直接按活动分组取第一行即可:
campaign_base = df.groupby(['Campaign Name', 'Campaign Start Date'])[['Product 1', 'Product 2', 'Product 3']].first().reset_index()
步骤3:映射生成价格列
遍历产品列,根据当前活动的价格映射匹配对应价格:
for i in range(1, 4): product_col = f'Product {i}' price_col = f'Product {i} Price' campaign_base[price_col] = campaign_base.apply( lambda row: price_maps[row['Campaign Name']].get(row[product_col], np.nan), axis=1 )
步骤4:调整数据类型(可选)
将价格列转换为数值类型,确保格式正确:
price_cols = [f'Product {i} Price' for i in range(1,4)] campaign_base[price_cols] = campaign_base[price_cols].apply(pd.to_numeric)
最终得到的campaign_base就是目标格式的DataFrame。
内容的提问来源于stack exchange,提问作者Sean R
相关产品推荐
相关产品推荐

