You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Power BI中按Segment展示趋势线公式与R²值的Python表格实现需求

批量生成各Segment趋势线统计表格的Python方案(Power BI Desktop适用)

以下代码会按Segment分组计算每组的线性/指数趋势线公式及R²值,最终输出结构化表格,直接在Power BI中加载即可展示所有Segment的统计结果:

# Power BI自动生成的预处理代码(保留)
# dataset = pandas.DataFrame(average sales per day, temperature_2m_max °C, Segment)
# dataset = dataset.drop_duplicates()

# 导入依赖库
import pandas as pd
import numpy as np

# 定义函数:计算单个Segment的趋势线参数与R²
def calculate_trendline_stats(group):
    x = group['temperature_2m_max °C']
    y = group['average sales per day']
    
    # 跳过数据量不足的组(至少2个数据点才能拟合趋势线)
    if len(x) < 2:
        return pd.Series({
            '线性趋势线公式': '数据不足',
            '线性R-squared值': None,
            '指数趋势线公式': '数据不足',
            '指数R-squared值': None
        })
    
    # 计算线性趋势线
    slope, intercept = np.polyfit(x, y, 1)
    y_pred_lin = slope * x + intercept
    # 线性R²计算
    ss_tot = np.sum((y - np.mean(y))**2)
    ss_res_lin = np.sum((y - y_pred_lin)**2)
    r_squared_lin = 1 - (ss_res_lin / ss_tot) if ss_tot != 0 else 0
    # 格式化线性公式
    linear_formula = f'y = {slope:.2f}x + {intercept:.2f}'
    
    # 计算指数趋势线(处理y为正的情况,避免log报错)
    if (y <= 0).any():
        exp_formula = 'y值非正无法拟合'
        r_squared_exp = None
    else:
        p = np.polyfit(x, np.log(y), deg=1)
        a = np.exp(p[1])
        b = p[0]
        y_pred_exp = a * np.exp(b * x)
        ss_res_exp = np.sum((y - y_pred_exp)**2)
        r_squared_exp = 1 - (ss_res_exp / ss_tot) if ss_tot != 0 else 0
        exp_formula = f'y = {a:.2f} * exp({b:.3f}x)'
    
    return pd.Series({
        '线性趋势线公式': linear_formula,
        '线性R-squared值': round(r_squared_lin, 4),
        '指数趋势线公式': exp_formula,
        '指数R-squared值': round(r_squared_exp, 4) if r_squared_exp is not None else None
    })

# 按Segment分组计算,合并结果
result_df = dataset.groupby('Segment').apply(calculate_trendline_stats).reset_index()

# 输出结果到Power BI
print(result_df)

代码说明:

  • 分组处理:通过groupby('Segment')遍历每个Segment的数据组,批量计算统计值
  • 异常处理:
    • 跳过数据点不足2个的Segment,避免拟合报错
    • 检查y值(日均销量)是否为正,避免指数拟合时np.log(y)报错
  • 格式化输出:趋势线公式保留指定小数位数,R²值保留4位小数,确保表格可读性
  • Power BI适配:最终输出的result_df会被Power BI自动识别为表格,直接加载即可创建可视化

内容的提问来源于stack exchange,提问作者Carlo Kramers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:22:17