有没有一种方法可以像在Excel中那样冻结Pandas数据框的表头呢?这样,即使是具有多行数据的长数据框,我们也可以在向下滚动时看到表头!我假设是在IPython笔记本上。
有没有一种方法可以像在Excel中那样冻结Pandas数据框的表头呢?这样,即使是具有多行数据的长数据框,我们也可以在向下滚动时看到表头!我假设是在IPython笔记本上。
这个函数可能就可以解决问题:
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)
虽然这是个老问题,但我想回顾一下,因为我最近找到了一个解决方案。使用qgrid模块:https://github.com/quantopian/qgrid
这不仅可以让您在滚动时固定标题,还可以进行排序、筛选、行内编辑和其他一些功能。非常有帮助。
试用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上没有)
df.ix[100:110] # would show you from row 101 to 110 keeping the header on top