我有一个 Pandas 数据框:
arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])
我想为“MOS”行中的所有值涂上某种颜色,并为左侧的两个索引/标题列以及顶部标题行涂上与其他具有值的单元格不同的背景颜色他们。我有什么想法可以做到这一点吗?
最佳答案
使用 Pandas 新styling功能(从 0.17.1 开始):
import numpy as np
import pandas as pd
arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])
def highlight_MOS(s):
is_mos = s.index.get_level_values(1) == 'MOS'
return ['color: darkorange' if v else 'color: darkblue' for v in is_mos]
s = df.style.apply(highlight_MOS)
s
关于python - 使用样式和 css 更改 pandas 数据框 html 表 python 中文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38511373/