Pandas 如何在style.apply之后显示大熊猫数据帧的截断形式?
通常,一个相对较长的数据帧Pandas 如何在style.apply之后显示大熊猫数据帧的截断形式?,pandas,Pandas,通常,一个相对较长的数据帧 df = pd.DataFrame(np.random.randint(0,10,(100,2))) df 将在jupyter笔记本中显示截断的表单,如 头、尾、省略号在中间,行-列计数在末尾。 但是,在style.apply之后 def highlight_max(x): return ['background-color: yellow' if v == x.max() else '' for v in x] df.style.apply(highli
df = pd.DataFrame(np.random.randint(0,10,(100,2)))
df
将在jupyter笔记本中显示截断的表单,如
头、尾、省略号在中间,行-列计数在末尾。
但是,在style.apply之后
def highlight_max(x):
return ['background-color: yellow' if v == x.max() else '' for v in x]
df.style.apply(highlight_max)
我们把所有的行都显示出来了
是否仍可以在样式后显示数据帧的截断形式。应用?您可以捕获变量中的输出,然后在其上使用
头
或尾
。这使您能够更好地控制每次显示的内容
output = df.style.apply(highlight_max)
output.head(10) # 10 -> number of rows to display
如果您想查看更多变量数据,还可以使用sample
,这将获得随机行:
output.sample(10)
像这样简单的事情
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:,:]]))
但如果您尝试应用样式,则会出现错误(“int”和“str”实例之间不支持“>=”),因为它试图比较并突出显示字符串值“…”您好,Carles Sala。谢谢你的回答。但我不是指头部或样本。我的意思是显示行和列的头、尾和基本信息的默认截断形式。您为什么要隐藏突出显示的行?@ScottBoston,因为行太多。这是一种可能的方式,但它不是带省略号的默认形式。感谢您+1熊猫样式方法应该应用于整个数据帧,以便您可以观察高亮显示的值。检查我编辑过的答案,这是最接近jupyter预览版的。