pandas.io.formats.style.Styler
Snippets
サンプル
import shirotsubaki.report
import pandas as pd
def sample_table_0():
df = pd.DataFrame({
'A': [1, -2, 3, 1, -2, 3],
'B': [-1, 2, -3, -1, 2, -3],
'C': [1, -2, 3, 1, -2, 3],
'D': [-1, 2, -3, -1, 2, -3],
'E': ['pineapple', 'apple'] * 3,
})
def color_negative(v, color):
# そのセルの値に応じてスタイルを適用するための関数
return f'color: {color};' if v < 0 else None
def highlight(row, cols):
# D列の値に応じてC列にスタイルを適用するための関数
return [
('background: pink;' if (row['D'] < 0) else None) if col == 'C' else None
for col in cols
]
styled = df.style.set_table_styles([
# 単に 表全体 / ヘッダ行 / i行目 / i列目 にスタイルを適用するときは以下が読みやすい
{'selector': 'th,td', 'props': [('min-width', '40px')]},
{'selector': 'th', 'props': [('background', 'lightgray')]},
{'selector': 'th.col4', 'props': [('background', 'dimgray')]},
*[
{'selector': f'td.col{i}', 'props': [('text-align', 'right')]}
for i in range(2)
],
{'selector': 'td.col4', 'props': [('background', 'azure')]},
{'selector': 'td.row4', 'props': [('background', 'lemonchiffon')]},
]).set_properties(
# ただし 複数行 / 複数列 にスタイルを適用するときは以下がすっきりする
subset=['C', 'D'], **{'text-align': 'right'},
).map(
# そのセルの値に応じてスタイルを適用するときは以下
subset=([0, 1, 2], ['A', 'B']), func=color_negative, color='red',
).apply(
# D列の値に応じてC列にスタイルを適用するときは以下
subset=['C', 'D'], func=highlight, cols=['C', 'D'], axis=1,
).hide(axis=0)
return styled.to_html()
if __name__ == '__main__':
rp = shirotsubaki.report.Report()
rp.append(sample_table_0())
rp.output('index.html')
A |
B |
C |
D |
E |
1 |
-1 |
1 |
-1 |
pineapple |
-2 |
2 |
-2 |
2 |
apple |
3 |
-3 |
3 |
-3 |
pineapple |
1 |
-1 |
1 |
-1 |
apple |
-2 |
2 |
-2 |
2 |
pineapple |
3 |
-3 |
3 |
-3 |
apple |
参考文献
-
pandas.io.formats.style.Styler — pandas 3.0.0.dev0+2276.g36b8f20e06 documentation.
(2025年07月30日参照).