Pandas DataFrame表格垂直滚动条

17

我有一个垂直方向很长的pandas数据框,希望以漂亮的表格形式展示,并带有滚动条。我可以将所有行显示为表格,但是无法显示滚动条。

def data(x):
    strData = strData[['Data1','Data2','Data3']]
    display(strData)

输出:没有垂直滚动条

在此输入图片描述

4个回答

21

我不确定这是否是您的意思,但我猜您需要将max_rows选项设置为None,以便pandas不会限制显示的行数:

pd.set_option("display.max_rows", None)

这里输入图片描述


更新:

In [27]: 
##javascript
IPython.OutputArea.auto_scroll_threshold = 10;

In[28]:
def display_():    
    pd.set_option("display.max_rows", None)
    from IPython.core.display import display 
    display(df) #df must be defined up there

在此输入图片描述


这正是我所需要的。我已经将它添加到代码中,但仍然显示所有行而没有滚动条。我尝试了print(strData)和函数内部的strData,但都不起作用。当它在函数内部时,它的行为是否会有所不同? - magicsword
刚在函数内测试过,对我有效。def display_(): pd.set_option("display.max_rows", None) from IPython.core.display import display display(df) - Psidom
1
30行还不足以触发Python笔记本的滚动条。您需要更改auto_scrolling的阈值。尝试更新的方法。 - Psidom
1
由于某种原因,JavaScript 行出现错误。 - adir abargil
上下文是什么?Jupyter笔记本还是Jupyter-lab? - James Hirschorn
显示剩余3条评论

16

另一个答案对我没用——IPython.OutputArea似乎不再存在(就我所知,至少在VSCode和基于IPython的代码中不再存在)。

我用一种比较巧妙的方法使一个数据框可以滚动:生成数据框的HTML表格,然后将其放入一个 div 中,可以使用CSS使其可滚动。在这种情况下,我们只需要将高度设置为某个像素值即可。

我们还可以将溢出设置为auto,宽度设置为fit-content,以便滚动条出现在数据框旁边,而不是窗口右侧。

import pandas as pd
from IPython.display import display, HTML

df = pd.DataFrame([(i, i) for i in range (20)])

pd.set_option("display.max_rows", None)

# Puts the scrollbar next to the DataFrame
display(HTML("<div style='height: 200px; overflow: auto; width: fit-content'>" +
             df.style.render() +
             "</div>"))

# Puts the scrollbar on the right side of the window
display(HTML("<div style='height: 200px'>" + df.style.render() + "</div>"))

演示:


这个方案非常好,我喜欢它!唯一的改变是将 height 替换为 max-height,以防止表格在其中有少量项目时占用不必要的空间:display(HTML("<div style='max-height: 400px'>" + pd.DataFrame(records, columns=columns).to_html() + "</div>")) - zaaath
这很不错。有没有办法用这个解决方案覆盖用于渲染pd.DataFrame的标准显示函数? - Bananeen

7

只需传入数据框,观察魔力。

def table(df):
    import plotly.graph_objs as go
    fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                align='left'),
    cells=dict(values=[df[i] for i in df.columns],           
                align='left'))
    ])
    return fig

2
能否解释一下为什么在这种情况下使用plotly是一个好的库,也许可以展示一下它看起来是什么样子? - totokaka
1
事实上,我在使用plotly时感觉非常舒适。它提供的信息比matplotlib和seaborn更加详细。当然,用户还可以根据需要选择其他库。 - ASAD ASHRAF KAREL
对我来说,这只是返回一个空单元格。在Jupyter Notebook 7.0.3上使用plotly-5.16.1。 - undefined
只适用于Jupyter Lab 4.0.5(因此不适用于Jupyter Notebook,仅适用于Jupyter Lab)。 - undefined

0
使用ipydatagrid
import string
import numpy as np
import pandas as pd

N = 5000
cols = {char:np.random.randn(N) for char in string.ascii_lowercase[:5]} 
df = pd.DataFrame(cols)

from ipydatagrid import DataGrid
DataGrid(df)

enter image description here


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