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

使用Pandas对多组数据集按产品、渠道及年份计算评分相关矩阵

解决方案

1. 数据预处理

首先确保Date列是datetime类型,这是使用resample的前提:

import pandas as pd

# 加载你的DataFrame(替换为实际数据读取方式)
df = pd.read_csv("your_data_source.csv")
df['Date'] = pd.to_datetime(df['Date'])

2. 按年份聚合评分均值

按Channel和Product分组后,对每个组的Rating按年度求均值,再将数据重塑为宽表(渠道为列、年份为行):

# 分组+年度聚合均值,再转换为宽表结构
annual_rating = (
    df.groupby(['Channel', 'Product'])['Rating']
      .resample('Y').mean()
      .reset_index()
      .pivot(index='Date', columns=['Product', 'Channel'], values='Rating')
)

3. 按产品分组计算渠道相关矩阵

遍历所有产品,提取对应渠道的评分数据,计算皮尔逊相关矩阵并按要求格式输出:

# 获取所有唯一产品
products = df['Product'].unique()

for product in products:
    # 提取当前产品的全渠道数据
    product_data = annual_rating[product]
    # 计算相关矩阵
    corr_matrix = product_data.corr()
    
    # 按指定格式输出
    print(f"{product}:")
    print(corr_matrix.round(2))  # 保留两位小数提升可读性
    print("\n")

输出示例

Pr1:
        Ch1    Ch2    Chn
Ch1    1.00   0.80  -0.30
Ch2    0.80   1.00   0.60
Chn   -0.30   0.60   1.00

Pr2:
        Ch1    Ch2    Chn
Ch1    1.00   0.40   0.50
Ch2    0.40   1.00  -0.10
Chn    0.50  -0.10   1.00
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:25:49