【问题标题】:How to show truncated form of large pandas dataframe after style.apply?如何在 style.apply 之后显示大熊猫数据框的截断形式?
【发布时间】:2020-05-25 00:36:09
【问题描述】:

通常,一个相对较长的数据帧,如

df = pd.DataFrame(np.random.randint(0,10,(100,2)))
df

将在 jupyter notebook 中显示截断的形式,如

中间有头、尾、省略号,最后是行列数。 但是,在 style.apply 之后

def highlight_max(x):
    return ['background-color: yellow' if v == x.max() else '' for v in x]
df.style.apply(highlight_max)

我们显示了所有行

在 style.apply 之后是否仍然可以显示截断形式的数据框?

【问题讨论】:

  • 为什么要隐藏突出显示的行?
  • @ScottBoston 因为行太多

标签: pandas


【解决方案1】:

您可以在变量中捕获输出,然后在其上使用headtail。这使您可以更好地控制每次显示的内容。

output = df.style.apply(highlight_max)
output.head(10)  # 10 -> number of rows to display

如果您想查看更多变量数据,您也可以使用sample,它将获得随机行:

output.sample(10)

【讨论】:

  • 嗨,卡尔斯·萨拉。谢谢您的回答。但我不是指头部或样本。我的意思是显示行和列的头、尾和基本信息的默认截断形式
【解决方案2】:

像这样简单的东西?

def display_df(dataframe, function):
    display(dataframe.head().style.apply(function))
    display(dataframe.tail().style.apply(function))
    print(f'{dataframe.shape[0]} rows x {dataframe.shape[1]} columns')

display_df(df, highlight_max)

输出:

**** 编辑 ****

def display_df(dataframe, function):
    display(pd.concat([dataframe.iloc[:5,:],
                       pd.DataFrame(index=['...'], columns=dataframe.columns),
                       dataframe.iloc[-5:,:]]).style.apply(function))
    print(f'{dataframe.shape[0]} rows x {dataframe.shape[1]} columns')

display_df(df, highlight_max)

输出:

jupyter 预览基本上是这样的:

def display_df(dataframe):
    display(pd.concat([dataframe.iloc[:5,:],
                       pd.DataFrame(index=['...'], columns=dataframe.columns, data={0: '...', 1: '...'}),
                       dataframe.iloc[-5:,:]]))

但是如果你尝试应用样式,你会得到一个错误(TypeError: '>=' not supported between 'int' and 'str')因为它试图比较和突出字符串值'...'

【讨论】:

  • 这是一种可能的方式,但它不是带有省略号的默认形式。谢谢+1
  • 熊猫样式方法应该应用于整个数据框,以便您可以观察突出显示的值。检查我编辑的答案,这是我能得到的最接近 jupyter 预览的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 2017-12-16
  • 2018-08-17
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多