在Pandas数据框中冻结标题行

30

有没有一种方法可以像在Excel中那样冻结Pandas数据框的表头呢?这样,即使是具有多行数据的长数据框,我们也可以在向下滚动时看到表头!我假设是在IPython笔记本上。


你最终解决了这个问题吗? - tmthyjames
我没有能够弄清楚。 - sushmit
4个回答

23

这个函数可能就可以解决问题:

from ipywidgets import interact, IntSlider
from IPython.display import display

def freeze_header(df, num_rows=30, num_columns=10, step_rows=1,
                  step_columns=1):
    """
    Freeze the headers (column and index names) of a Pandas DataFrame. A widget
    enables to slide through the rows and columns.

    Parameters
    ----------
    df : Pandas DataFrame
        DataFrame to display
    num_rows : int, optional
        Number of rows to display
    num_columns : int, optional
        Number of columns to display
    step_rows : int, optional
        Step in the rows
    step_columns : int, optional
        Step in the columns

    Returns
    -------
    Displays the DataFrame with the widget
    """
    @interact(last_row=IntSlider(min=min(num_rows, df.shape[0]),
                                 max=df.shape[0],
                                 step=step_rows,
                                 description='rows',
                                 readout=False,
                                 disabled=False,
                                 continuous_update=True,
                                 orientation='horizontal',
                                 slider_color='purple'),
              last_column=IntSlider(min=min(num_columns, df.shape[1]),
                                    max=df.shape[1],
                                    step=step_columns,
                                    description='columns',
                                    readout=False,
                                    disabled=False,
                                    continuous_update=True,
                                    orientation='horizontal',
                                    slider_color='purple'))
    def _freeze_header(last_row, last_column):
        display(df.iloc[max(0, last_row-num_rows):last_row,
                        max(0, last_column-num_columns):last_column])

使用以下方式进行测试:

import pandas as pd
df = pd.DataFrame(pd.np.random.RandomState(seed=0).randint(low=0,
                                                           high=100,
                                                           size=[200, 50]))
freeze_header(df=df, num_rows=10)

这导致了(颜色是在~/.jupyter/custom/custom.css文件中自定义的): 输入图像描述


不错的解决方案,但是如果你的数据在宽度上波动(例如一个100个字符的字符串和一个20个字符的字符串),那么当你滚动时列会跳来跳去,这使得跟踪变得困难。对此有什么想法吗? - Chris Decker
这很棒,但它会丢失pandas数据框的样式。例如,我正在尝试生成的热图不再生效。corr.style.background_gradient(cmap='coolwarm').set_precision(2) - Riley Hun

10

虽然这是个老问题,但我想回顾一下,因为我最近找到了一个解决方案。使用qgrid模块:https://github.com/quantopian/qgrid

这不仅可以让您在滚动时固定标题,还可以进行排序、筛选、行内编辑和其他一些功能。非常有帮助。


2
这对我有用。但是请注意,Qgrid在其Github页面上未经过Jupyter lab 3.0测试。因此,如果使用Jupyter lab 3,请尝试在此处列出的安装方法https://github.com/quantopian/qgrid/issues/350。 - RAVI D PARIKH

7

试用Panda的固定表头功能:

import pandas as pd
import numpy as np

bigdf = pd.DataFrame(np.random.randn(16, 100))
bigdf.style.set_sticky(axis="index")

(这个功能是最近引入的,我发现它在pandas 1.3.1上工作,但在1.2.4上没有)


1
这里包含类似于上面的代码,但实际上可以在我的Jupyter版本中工作。https://github.com/pandas-dev/pandas/issues/29072 - Chris
属性错误:'Styler'对象没有属性'set_sticky'。 - pdangelo4

0
一个适用于任何编辑器的解决方案是选择你想查看的行:
df.ix[100:110] # would show you from row 101 to 110 keeping the header on top

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接