pandas - 如何在style.apply之后显示 Pandas 数据框的截断形式?

标签 pandas

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

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

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

enter image description here

头、尾、省略号在中间,行列数在最后。
但是,在 style.apply 之后
def highlight_max(x):
    return ['background-color: yellow' if v == x.max() else '' for v in x]
df.style.apply(highlight_max)

我们显示了所有行

enter image description here

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

最佳答案

这么简单的事?

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)

输出:

enter image description here

**** 编辑 ****
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)

输出:

enter image description here

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' 和 'str'),因为它正在尝试比较和突出显示字符串值 '...'

关于pandas - 如何在style.apply之后显示 Pandas 数据框的截断形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137757/

相关文章:

python - 如何将 iPython HTML 类发送到 .html 文件?

python - 范围 Pandas 之间字典中的查找值

python - 如何以简单的方式删除 pandas 数据框中的特殊行

python - 将整列追加到字典中

python - 在索引数据帧后更新 Pandas MultiIndex

excel - 版本 0.15.2 中的 pandas to_excel 不适用于日期时间对象

python - Pandas 两个excel列比较中的一对多比较?

python - 从包含字典的命名元组创建数据帧

python - 前向填充上述值 pandas 的 block

python - 使用 Pandas DataFrame 进行迭代并更改值