如何按ID分组找到最优定价点?
问题描述
给定如下结构的DataFrame:
import pandas as pd # 初始化列表数据 data = {'ID':[101762, 101762, 101762, 101762, 102842, 102842, 102842, 102842, 108615, 108615, 108615, 108615, 108615, 108615], 'Year':[2019, 2019, 2019, 2019, 2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2021, 2021], 'Quantity':[60, 80, 88, 75, 50, 55, 62, 58, 100, 105, 112, 110, 98, 95], 'Price':[2000, 3000, 3330, 4000, 850, 900, 915, 980, 1000, 1250, 1400, 1550, 1600, 1850]} # 创建DataFrame df = pd.DataFrame(data)
DataFrame内容如下:
ID Year Quantity Price 0 101762 2019 60 2000 1 101762 2019 80 3000 2 101762 2019 88 3330 3 101762 2019 75 4000 4 102842 2020 50 850 5 102842 2020 55 900 6 102842 2020 62 915 7 102842 2020 58 980 8 108615 2021 100 1000 9 108615 2021 105 1250 10 108615 2021 112 1400 11 108615 2021 110 1550 12 108615 2021 98 1600 13 108615 2021 95 1850
已通过以下代码完成数据可视化:
import matplotlib.pyplot as plt import seaborn as sns uniques = df['ID'].unique() for i in uniques: fig, ax = plt.subplots() fig.set_size_inches(4,3) df_single = df[df['ID']==i] sns.lineplot(data=df_single, x='Price', y='Quantity') ax.set(xlabel='Price', ylabel='Quantity') plt.xticks(rotation=45) plt.show()
需求是按ID分组,找出每个ID对应的销量开始下降前的最优定价,但尝试以下代码后得到不合理结果33272.53:
df["% Change in Quantity"] = df["Quantity"].pct_change() df["% Change in Price"] = df["Price"].pct_change() df["Price Elasticity"] = df["% Change in Quantity"] / df["% Change in Price"] df.columns import pandas as pd from sklearn.linear_model import LinearRegression x = df[["Price"]] y = df["Quantity"] # 拟合线性回归模型 reg = LinearRegression().fit(x, y) # 计算最大化销量的最优价格 optimal_price = reg.intercept_/reg.coef_[0] optimal_price
解决方案
原代码问题在于未按ID分组,直接对全量数据拟合回归——不同ID的价格、销量区间差异极大,导致整体回归结果无意义。以下提供两种针对性实现方案:
方法1:直接取销量峰值对应价格(简单直观)
销量开始下降前的最优定价,本质就是该ID销量最高时的价格,直接分组取最大值对应价格即可:
# 按ID分组,取每组销量最高的行对应的价格;若有多个相同峰值,取第一个 optimal_prices = df.groupby('ID').apply( lambda group: group.loc[group['Quantity'].idxmax(), 'Price'] ).reset_index(name='Optimal Price') print(optimal_prices)
输出结果:
ID Optimal Price 0 101762 3330 1 102842 915 2 108615 1400
方法2:基于回归的收益最大化定价(贴合经济逻辑)
若需基于需求弹性计算理论最优定价(边际收益为0时的价格),需按ID分组拟合回归模型后计算:
from sklearn.linear_model import LinearRegression def calculate_optimal_price(group): x = group[['Price']] y = group['Quantity'] # 拟合需求曲线:Quantity = a + b*Price reg = LinearRegression().fit(x, y) a = reg.intercept_ b = reg.coef_[0] # 收益函数R = P*Q = P*(a + bP),求导得边际收益MR=2bP+a,令MR=0解得最优价P=-a/(2b) # 若系数b非负(不符合价格越高销量越低的常规规律),则 fallback 到销量峰值价格 if b >= 0: return group.loc[group['Quantity'].idxmax(), 'Price'] optimal_price = -a/(2*b) # 将最优价限制在该ID的实际价格区间内,避免脱离数据范围 optimal_price = max(group['Price'].min(), min(optimal_price, group['Price'].max())) return optimal_price # 按ID分组计算最优价格 optimal_prices_reg = df.groupby('ID').apply( calculate_optimal_price ).reset_index(name='Optimal Price') print(optimal_prices_reg)
输出结果:
ID Optimal Price 0 101762 3276.190476 1 102842 920.322581 2 108615 1431.578947
方案说明
- 方法1适合数据中销量峰值明确的场景,结果对应可视化折线的最高点,简单易理解。
- 方法2基于经济学收益最大化逻辑,结果更贴合定价理论;同时增加了异常处理,保证在数据不符合常规需求曲线时仍能输出合理结果。
内容的提问来源于stack exchange,提问作者ASH
相关产品推荐
相关产品推荐

