简而言之,我的目标是在我的 html 页面中显示一个看起来“正常”的表格(也就是所有标题都在一行上,没有行号)并且每个单元格都根据规则查找进行颜色编码(需要灵活性为每个单元格查找不同的规则。)我的数据存储在 pd.DataFrame 对象中。有时我的数据可以更好地表示为数据透视表(多个索引)。格式是最终用户的要求。文件系统访问非常有限,所有这些都是多线程的,所以我真的没有选择先写 html 然后读-修改-写。
运行环境的一些信息:
- Python 3.5.2
- 熊猫版本 0.19.2
- 需要在 x86 和 x64 上运行
- 需要在windows和linux上运行
示例设置:
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['special_col_1'] = pd.Series([0,0,0,1,1,1])
df['special_col_2'] = pd.Series([0,1,2,0,1,2])
df['a'] = pd.Series(np.random.randn(6)).apply(lambda x: int(x*100))
df['b'] = pd.Series(np.random.randn(6)).apply(lambda x: int(x*100))
df['c'] = pd.Series(np.random.randn(6)).apply(lambda x: int(x*100))
basic_limits = {'a': lambda x: 'background-color: red' if x < 0 else 'background-color: green',\
'b': lambda x: 'background-color: red' if x < 10 else 'background-color: green', \
'c': lambda x: 'background-color: red' if x > 20 else 'background-color: green', \
'special_col_1': lambda x: 'background-color: white', \
'special_col_2': lambda x: 'background-color: white'}
我尝试过的示例以及我不喜欢它们的原因:
df.to_html(index=False)
一切都正确布局
找不到任何方法为每个单元格应用 css
pd.pivot_table(data=df, columns=['special_col_1', 'special_col_2']).to_html(index=False)
布局不正确,第一行应包含所有标签
找不到任何方法为每个单元格应用 css
dfs = df.style
for col in df.columns:
dfs.applymap(basic_limits[col], subset=col)
不正确的布局 - 不应该有行号(索引),但是一旦你从 pd.DataFrame 转到 pd.DataFrame.Styler 就找不到任何删除索引的方法
可以使用 lambda 函数的 dict 正确应用 css 样式
可以修改为对行和列进行迭代,并且 applymap() 仍然可以工作(需要更复杂的 lambda 函数的多级字典)
df.pivot_table(data=df, columns=???).style(...)
指定 ['special_col_1', 'special_col_2'] 再次破坏顶行的格式
不指定任何列是不可接受的('ValueError: No group keys pass!')
具有作为 pd.DataFrame.Styler 的所有优点和缺点目的
任何帮助将不胜感激!抱歉,我不能包含表格的图像,这是我的第一篇文章。
确认的工作答案(piRSquared)提供了我正在寻找的灵活性:
df = pd.DataFrame()
dfs = df.style
#iterate through dataframe's columns, applying custom function to each cell in the column
for col in df.columns:
dfs.applymap(cell_based_function_dict[col], subset=col)
#apply a function to each column
col_based_function = lambda c: pd.Series(['background-color: white' if c.name in ['special_col_1', 'special_col_2'] else 'background-color: red' if x == c.max() else 'background-color: orange' if x > 0 else 'background-color: green' for x in c])
dfs.apply(col_based_function)
#define css specifics for this particular table
styler.set_table_styles([\
{'selector': 'tr :first-child', 'props': [('display', 'none')]}, \
{'selector': 'tr:hover td', 'props': [('background-color', 'yellow')]}, \
{'selector': 'th, td', 'props': [('border', '1px solid black'), \
('padding', '4px'), \
('text-align', 'center')]}, \
{'selector': 'th', 'props': [('font-weight', 'bold')]}, \
{'selector': '', 'props': [('border-collapse', 'collapse'),\
('border', '1px solid black')]} \
])
#all the styling appears to be tied only to this particular dataframe table, so you can easily call render() on different tables of different styles
dfs.render()