问题描述
我跑步时
import pandas as pd
from IPython.display import display
df = pd.DataFrame('a',index=pd.MultiIndex.from_product([[0,1]]*3),columns=['A'])
display(df)
display(df.style.apply(lambda x: ['']*len(x),axis=1))
在Jupyter中,我得到以下显示(很遗憾,我无法上传屏幕截图)
in Jupyter, I get the following displays (unfortunately I cannot upload screenshots)
0 0 0 a
1 a
1 0 a
1 a
1 0 0 a
1 a
1 0 a
1 a
-
0 a
0
1 a
0
0 a
1
1 a
0 a
0
1 a
1
0 a
1
1 a
1:如何防止该更改?
2:由于我实际上并不完全不喜欢第二种格式:如何固定多索引的背景,以使每个多索引级别的组的边界在视觉上清晰可见?
(PS:在我的实际代码中,lambda在某些行上返回'background: green'
)
(PS: In my actual code, the lambda returns 'background: green'
for some rows)
推荐答案
有关GitHub的一些相关讨论此处和此处有关默认设置vertical-alignment
应该应用于th
的CSS属性;我认为这些CSS样式应该为您提供一个良好的起点:
There is a bit of relevant discussion on GitHub here and here regarding the default vertical-alignment
CSS attribute that should be applied to th
's; I think these CSS styles should give you a good starting point:
s=df.style.set_table_styles([
{'selector': 'th',
'props': [
('border-style', 'solid'),
('border-color', 'Red'),
('vertical-align','top')
]
}]
)
HTML(s.render())
这将使MultiIndices高度对齐,并为其赋予红色边框.
This would top-align the MultiIndices, and give them a red border.
更新
我不知道您如何评估样式/条件,但是如果您的DF中有一些"b"(例如df.loc[0,0,1]='b'
,df.loc[1,0,1]='b'
),则可以定义一个样式功能,例如:
I don't know how you're evaluating your style/conditions, but if you had some 'b's in your DF (e.g. df.loc[0,0,1]='b'
, df.loc[1,0,1]='b'
) then you could define a styling function like:
def color_b_green(value):
if value == 'b':
color = 'blue'
else:
color = 'black'
return 'color: %s' % color
最后将所有内容链接在一起(在这里清理),如下所示:
and finally chain everything together (cleaned up here) like:
styles=[
{'selector': 'th',
'props': [
('border-style', 'solid'),
('border-color', 'Red'),
('vertical-align','top')
]
}]
(df.style
.apply(lambda x: ['']*len(x),axis=1)
.applymap(color_b_green)
.set_table_styles(styles))
这篇关于df.style.apply使显示中的多索引值居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!