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

如何仅用Polars从整洁/长格式pl.DataFrame直接创建热力图

基于Polars长格式DataFrame创建热力图的简化方案

Polars本身不内置可视化功能,无法完全脱离第三方绘图库生成热力图,但我们可以简化原有流程,全程用Polars处理数据,无需手动转换为Pandas格式,直接对接Plotly完成绘图:

简化实现代码

import plotly.express as px
import polars as pl

# 原始长格式Polars DataFrame
tidy_df_pl = pl.DataFrame(
    {
        "x": [10, 10, 10, 20, 20, 20, 30, 30, 30],
        "y": [3, 4, 5, 3, 4, 5, 3, 4, 5],
        "value": [5, 8, 2, 4, 10, 14, 10, 8, 9],
    }
)

# 用Polars原生pivot生成宽格式并设置索引
pivot_df_pl = tidy_df_pl.pivot(index="x", on="y", values="value").set_index("x")

# Plotly直接读取Polars DataFrame生成热力图
fig = px.imshow(pivot_df_pl)
fig.show()

核心优化点

  • 跳过to_pandas()转换:Plotly的px.imshow支持直接传入Polars DataFrame,无需手动转成Pandas格式。
  • 全程Polars处理:数据透视、索引设置都用Polars原生API完成,保持数据处理的一致性。

注意:如果完全不使用任何第三方绘图库,Polars没有生成可视化图表的能力,它仅专注于数据处理逻辑,热力图的渲染必须依赖Plotly、Matplotlib这类专业绘图工具。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:23:24