python - How to style the first index in a multi-index DataFrame
问题描述
I have the following DataFrame:
Cluster 0 (N=1286)
a bmi 28.21 (25.01, 30.48)
gender (f) 67 (5.21%)
b APACHE 17.75 (15.0, 21.0)
ASTP 4.66 (3.0, 7.0)
age 62.92 (57.0, 72.0)
Code for this DataFrame:
df = pd.DataFrame( {'Cluster 0 (N=1286)': {('a', 'gender (f)'): '67 (5.21%)', ('a', 'bmi'): '28.21 (25.01, 30.48)', ('b', 'age'): '62.92 (57.0, 72.0)', ('b', 'ASTP'): '4.66 (3.0, 7.0)', ('b', 'APACHE'): '17.75 (15.0, 21.0)'}})
The DataFrame has two indices: a and b on the first level, and 'bmi', 'gender', ..., on the second level. Normally, a DataFrame alternates the background-color of the rows with white/light grey. I want to change this so that the a/b levels alternate with background colors white/light grey.
It should look like this:
解决方案
你可以试试这个:
def color(x):
return [
"background-color: lightgrey" if df.index[i][0] == "b" else ""
for i in range(0, len(df))
]
df.style.apply(func=color, axis=0)
# If you run the code in a Jupyter cell, it outputs
# the dataframe with lines "b" greyed.
请注意,根据Pandas 文档,“您只能设置值的样式,而不能设置索引或列的样式”。
推荐阅读
- javascript - 循环遍历对象数组以创建列表数组
- javascript - React - 如何使用媒体查询更改状态
- wordpress - A如何在WordPress的kona主题中将菜单条与滑块分开?
- macos - 如何将私人文件夹的权限从管理员更改为轮子
- typescript - TypeScript:输入模拟函数
- react-native - 在 FlatList 中每隔一定数量的项目后显示不同的组件
- bash - docker login 错误保存凭据:写入权限错误
- java - 如何使用 Selenium 默认启用地理位置?
- r - readOGR 和 st_read 的区别
- javascript - 当达到 0 时,我将如何在这里使用 clearInterval() 来停止计时器?