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

如何使用pandas将dataframe转为填充0的矩阵并绘制heatmap?

如何用Pandas将长格式DataFrame转换为矩阵形式并绘制热图?

当然可以!这其实是个非常常见的需求,用Pandas的内置工具就能轻松完成第一步的矩阵转换,再结合可视化库就能画出热图。我给你一步步说明:

第一步:转换为矩阵形式(填充缺失值为0)

你需要用Pandas的pivot_table函数,它专门用来处理这种长表转宽表的场景,还能直接帮你填充缺失值。先看完整代码:

import pandas as pd

# 构造你提供的原始数据
df = pd.DataFrame({
    'colA': ['car1', 'car2', 'car1', 'car2'],
    'colB': ['plane1', 'plane2', 'plane2', 'plane3'],
    'counts': [23, 51, 12, 41]
})

# 转换为矩阵形式,缺失值自动填充为0
matrix_df = df.pivot_table(
    index='colA',    # 行索引设为colA的取值(car1、car2)
    columns='colB',  # 列名设为colB的取值(plane1、plane2、plane3)
    values='counts', # 单元格填充counts列的数值
    fill_value=0     # 缺失的位置直接填0
)

print(matrix_df)

运行这段代码后,输出的matrix_df就是你想要的结果:

colB  plane1  plane2  plane3
colA                        
car1      23      12       0
car2       0      51      41

第二步:绘制热图

要画热图的话,用Seaborn库会非常方便(它基于Matplotlib,和Pandas兼容性很好)。代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

# 设置画布大小
plt.figure(figsize=(8, 6))

# 绘制热图,annot=True会显示单元格内的数值,fmt='d'表示用整数格式
sns.heatmap(matrix_df, annot=True, cmap='YlGnBu', fmt='d')

# 添加标题
plt.title('Car vs Plane Counts Heatmap')

# 显示图形
plt.show()

这段代码会生成一个带有数值标注的热图,颜色深浅对应数值大小,直观展示不同car和plane组合的counts数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:38:16