Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python df.style.apply在显示中居中多索引值_Python_Pandas_Jupyter - Fatal编程技术网

Python df.style.apply在显示中居中多索引值

Python df.style.apply在显示中居中多索引值,python,pandas,jupyter,Python,Pandas,Jupyter,当我跑的时候 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中,我得到以下显示(不幸的是,我无法上传屏幕截图) - 1:如

当我跑的时候

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中,我得到以下显示(不幸的是,我无法上传屏幕截图)

-

1:如何防止这种变化?

2:因为我实际上并不完全不喜欢第二种格式:我如何修复多重索引中的背景,使每个多重索引级别中的组边界在视觉上变得清晰?


(注:在我的实际代码中,lambda对某些行返回
'background:green'

关于GitHub和应该应用于
th
的默认
垂直对齐
CSS属性有一些相关的讨论;我认为这些CSS样式应该为您提供一个良好的起点:

s=df.style.set\u table\u样式([
{'selector':'th',
“道具”:[
(“边框样式”、“实体”),
(“边框颜色”、“红色”),
(“垂直对齐”、“顶部对齐”)
]
}]
)
HTML(s.render())
这将使多重索引顶部对齐,并给它们一个红色边框

更新

我不知道您是如何评估您的样式/条件的,但是如果您的DF中有一些“b”(例如,
DF.loc[0,0,1]=“b”
DF.loc[1,0,1]=“b”
),那么您可以定义一个样式函数,如:

def color\u b\u green(值):
如果值=='b':
颜色=‘蓝色’
其他:
颜色=‘黑色’
返回“颜色:%s”%color
最后把所有东西连在一起(在这里清理干净),比如:

样式=[
{'selector':'th',
“道具”:[
(“边框样式”、“实体”),
(“边框颜色”、“红色”),
(“垂直对齐”、“顶部对齐”)
]
}]
(df.style)
.应用(λx:['']*len(x),轴=1)
.applymap(颜色为绿色)
.set_表_样式(样式))

如何将其与使用style.apply进行的样式更改结合起来?我不能仅仅链接它,因为
Styler对象没有属性style
@Bananach我已经更新了我的答案来展示如何链接样式;我不知道您现在是如何应用这些东西的,但我想这是使用函数进行样式设置的最干净的方法(因此增加了
.applymap()
)。
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