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

如何用Polars实现Pandas中用户与游戏的相关性计算?

在Polars中计算用户间与游戏间的相关性

问题背景

我有一个记录用户游戏时长的数据集,需要计算用户间和游戏间的相关性。在Pandas中,我将user列设为索引后,用以下代码实现:

Pandas中用户间相关性计算代码

user_user_corr = user_game_df.T.corr()
user_user_corr.index = user_user_corr['Unnamed: 0'].values
user_user_corr.drop('Unnamed: 0', axis=1, inplace=True)
user_user_corr

Pandas中游戏间相关性计算代码

game_game_corr = user_game_df.corr()
game_game_corr.index = game_game_corr['Unnamed: 0'].values
game_game_corr.drop('Unnamed: 0', axis=1, inplace=True)
game_game_corr

我尝试用df.pearson_corr(...)和df.select(pl.pearson_corr(...))实现但未成功,请问如何用Polars完成该需求?


Polars实现方案

Polars的API逻辑和Pandas略有差异,通过转置+批量计算相关系数+结构调整即可实现需求:

1. 计算用户间相关性

假设你的Polars DataFrame(pl_df)结构为:user列存储用户ID,其余列是不同游戏的时长数据。

import polars as pl

# 转置DataFrame,让用户ID成为列名
transposed = pl_df.transpose(include_header=True, column_names=pl_df["user"].to_list())

# 计算列间Pearson相关系数,再转置回矩阵格式
user_user_corr_pl = (
    transposed
    .select(pl.all().pearson_corr(pl.all()))
    .transpose(include_header=True, column_names=pl_df["user"].to_list())
)

# 将用户ID设为索引,和Pandas结果结构对齐
user_user_corr_pl = user_user_corr_pl.with_columns(pl.col("column").alias("user")).set_index("user")

2. 计算游戏间相关性

直接对游戏时长列批量计算相关系数即可:

# 筛选出所有游戏时长列(排除user列)
game_cols = [col for col in pl_df.columns if col != "user"]

# 计算游戏列间的相关性矩阵
game_game_corr_pl = (
    pl_df.select(game_cols)
    .select(pl.all().pearson_corr(pl.all()))
    .transpose(include_header=True, column_names=game_cols)
)

# 将游戏名称设为索引
game_game_corr_pl = game_game_corr_pl.with_columns(pl.col("column").alias("game")).set_index("game")

关键说明

  • Polars的pearson_corr会返回行式的相关结果,需要通过transpose转置为标准矩阵格式
  • 转置时通过column_names参数指定列名,保证矩阵的行/列对应正确的用户/游戏标识
  • 最后用set_index把用户/游戏列设为索引,和Pandas的输出结构保持一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:07:16