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

如何将Pandas相关性矩阵的列名旋转90度?

Pandas相关性矩阵列名90度旋转实现方法

问题场景

生成Pandas相关性矩阵后,需要将表格列名旋转90度,但添加set_table_styles的代码未生效,原尝试代码如下:

import pandas as pd
import numpy as np

rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
corr = df.corr()
corr.style.set_table_styles(
    [dict(selector="th",props=[('max-width', '80px')]),
        dict(selector="corr.col_heading",
                 props=[("writing-mode", "vertical-rl"), 
                        ('transform', 'rotateZ(-90deg)'),
                        ])])
corr.style.background_gradient(cmap='coolwarm')

问题原因

  1. Styler实例未链式调用:每次调用corr.style都会生成新的Styler对象,分开调用set_table_styles和background_gradient会导致样式设置丢失。
  2. CSS选择器错误:列标题的正确选择器应为th.col_heading,而非corr.col_heading,错误的选择器无法匹配目标元素。
  3. 旋转样式冲突:同时设置writing-mode和transform会导致样式冲突,只需保留transform即可实现90度旋转。

解决代码

import pandas as pd
import numpy as np

rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
corr = df.corr()

# 链式调用Styler方法,确保样式生效
styled_table = corr.style.set_table_styles(
    [
        # 设置表头单元格基础样式
        dict(selector="th", props=[
            ('max-width', '80px'),
            ('height', '120px'),  # 增加高度避免旋转后内容截断
            ('text-align', 'center')
        ]),
        # 针对列标题设置90度旋转
        dict(selector="th.col_heading", props=[
            ('transform', 'rotate(90deg)'),
            ('transform-origin', 'center center')  # 设定旋转原点
        ])
    ]
).background_gradient(cmap='coolwarm')

# 显示表格
styled_table

关键说明

  • 链式调用:将set_table_styles和background_gradient通过.连接,确保样式应用到同一个Styler实例。
  • 精准选择器:th.col_heading可精准匹配相关性矩阵的列标题单元格。
  • 样式优化:设置height保证旋转后的列标题有足够显示空间,transform-origin确保旋转中心位置正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:58:38