Warning: Undefined variable $position in /home/pystyles/pystyle.info/public_html/wp/wp-content/themes/lionblog/functions.php on line 4897

pandas – テーブルの表示をカスタマイズする方法

pandas – テーブルの表示をカスタマイズする方法

概要

pandas の Styler オブジェクトで Jupyter Notebook に表示されるテーブルの見た目をカスタマイズする方法について解説します。

Advertisement

Styler オブジェクト

DataFrame.style 属性で DataFrame のスタイルを表す Styler オブジェクトを取得できます。

In [1]:
import numpy as np
import pandas as pd
from IPython.display import display, HTML

df = pd.DataFrame(
    [
        [11, None, 15, 4, 5],
        [2, 12, 10, 8, 16],
        [17, 24, 14, 13, 23],
        [19, 6, 18, None, 7],
        [3, 9, 20, 21, 1],
    ],
    index=["a", "b", "c", "d", "e"],
    columns=["A", "B", "C", "D", "E"],
)
df
A B C D E
a 11 NaN 15 4.0 5
b 2 12.0 10 8.0 16
c 17 24.0 14 13.0 23
d 19 6.0 18 NaN 7
e 3 9.0 20 21.0 1
In [2]:
print(type(df.style))
<class 'pandas.io.formats.style.Styler'>

Styler オブジェクトの関数は、スタイルを変更した Styler オブジェクトを返すようになっています。Jupyter Notebook の場合、このオブジェクトを DataFrame と同様にそのまま出力できます。

In [3]:
style = df.style.highlight_null()
print(type(style))

style
<class 'pandas.io.formats.style.Styler'>
A B C D E
a 11 nan 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 nan 7
e 3 9.000000 20 21.000000 1

複数の変更を適用する場合は、数珠繋ぎで呼び出せます。

In [4]:
style = (
    df.style.highlight_null().highlight_min(color="green").highlight_max(color="blue")
)
style
A B C D E
a 11 nan 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 nan 7
e 3 9.000000 20 21.000000 1

強調表示

欠損値を強調する

Styler.highlight_null() で欠損値を強調表示できます。

In [5]:
style = df.style.highlight_null("red")
A B C D E
a 11 nan 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 nan 7
e 3 9.000000 20 21.000000 1

列ごとに最小値を強調する

Styler.highlight_max() で列ごとに最小値を強調表示できます。

  • color: 色
  • axis: 適用する方向
  • subset: 特定のインデックスにのみ適用する場合は指定する
In [6]:
df.style.highlight_min(color="green")
A B C D E
a 11 nan 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 nan 7
e 3 9.000000 20 21.000000 1
Advertisement

列ごとに最大値を強調する

Styler.highlight_max() で列ごとに最大値を強調表示できます。

  • color: 色
In [7]:
df.style.highlight_max(color="green")
A B C D E
a 11 nan 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 nan 7
e 3 9.000000 20 21.000000 1

値の大きさに応じて、背景にバーを表示する

Styler.bar() で値の大きさに応じて、背景にバーを表示できます。

In [8]:
df = pd.DataFrame(
    {
        "A": [132, -107, -162, 96, 145, -133, 12, 35, 168, -12],
        "B": [0, -143, 21, 10, 105, 56, 120, 103, -132, 63],
        "C": [-31, 56, 67, 0, 16, 139, 0, -38, 142, -58]
    }
)

df.style.bar(color=["red", "green"], align="mid")
A B C
0 132 0 -31
1 -107 -143 56
2 -162 21 67
3 96 10 0
4 145 105 16
5 -133 56 139
6 12 120 0
7 35 103 -38
8 168 -132 142
9 -12 63 -58

値の大きさに応じてグラデーションする

Styler.background_gradien() で列ごとに値の大きさに応じて色分けできます。

  • cmap: カラーマップ名
  • text_color_threshold: テキストを黒白のどちらで表示するかを判断する際の閾値
  • vmin, vmax: カラーマップの値の範囲
In [9]:
df = pd.DataFrame(
    np.arange(25).reshape(5, 5),
    index=["a", "b", "c", "d", "e"],
    columns=["A", "B", "C", "D", "E"],
)
# 列ごと
display(df.style.background_gradient(axis=0))

# 行ごと
display(df.style.background_gradient(axis=1))
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24

書式を設定する

Advertisement

小数点の表示桁数を設定する

Styler.set_precision() で小数点以下の表示桁数を設定できます。

In [10]:
df = pd.DataFrame(
    [
        [11, None, 15, 4, 5],
        [2, 12, 10, 8, 16],
        [17, 24, 14, 13, 23],
        [19, 6, 18, None, 7],
        [3, 9, 20, 21, 1],
    ],
    index=["a", "b", "c", "d", "e"],
    columns=["A", "B", "C", "D", "E"],
)

df.style.set_precision(2)
A B C D E
a 11 nan 15 4.00 5
b 2 12.00 10 8.00 16
c 17 24.00 14 13.00 23
d 19 6.00 18 nan 7
e 3 9.00 20 21.00 1

書式を設定する

Styler.format() で書式を設定できます。 na_rep で欠損値の表示方法も合わせて設定できます。

In [11]:
df2 = (df / df.sum(axis=0))

df2.style.format("{:.0%}", na_rep="-")
A B C D E
a 21% 19% 9% 10%
b 4% 24% 13% 17% 31%
c 33% 47% 18% 28% 44%
d 37% 12% 23% 13%
e 6% 18% 26% 46% 2%

dict を使って列ごとに異なる書式を設定することもできます。

In [12]:
df2.style.format({"A": "{:.0%}", "B": "{:.2%}"}, na_rep="-")
A B C D E
a 21% 0.194805 0.086957 0.096154
b 4% 23.53% 0.129870 0.173913 0.307692
c 33% 47.06% 0.181818 0.282609 0.442308
d 37% 11.76% 0.233766 nan 0.134615
e 6% 17.65% 0.259740 0.456522 0.019231

欠損値の表示方法を設定する

Styler.set_na_rep() で欠損値の表示方法を設定できます。

In [13]:
df.style.set_na_rep("-")
A B C D E
a 11 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 7
e 3 9.000000 20 21.000000 1

テーブルにタイトルを設定する

Styler.set_caption() でテーブルにタイトルを設定できます。

In [14]:
df.style.set_caption("タイトル")
タイトル
A B C D E
a 11 nan 15 4.000000 5
b 2 12.000000 10 8.000000 16
c 17 24.000000 14 13.000000 23
d 19 6.000000 18 nan 7
e 3 9.000000 20 21.000000 1
Advertisement

HTML で出力する

Styler.render() で Style オブジェクトを HTML テーブルとして出力できます。

In [15]:
df = pd.DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])

style = df.style.background_gradient()
HTML(style.render())
A B
a 1 2
b 3 4

出力されたテーブルには id 属性に UUID が設定されており、各セルにも一意となる id 属性が設定されています。 自動で割り当てられる UUID の代わりに Styler.set_uuid() で id 属性に設定する値を指定できます。

In [16]:
style = df.style.background_gradient().set_uuid("hoge")
HTML(style.render())
A B
a 1 2
b 3 4

スタイルをクリアする

.Styler.clear() でスタイルをクリアします。

In [17]:
style = df.style.background_gradient()
display(style)

style.clear()
display(style)
A B
a 1 2
b 3 4
A B
a 1 2
b 3 4

特定の範囲に設定する

subset にスタイルを適用する範囲を以下で指定します。

  • 列名
  • 列名の一覧
  • pd.IndexSlice オブジェクト
In [18]:
df = pd.DataFrame(
    np.arange(25).reshape(5, 5),
    index=["a", "b", "c", "d", "e"],
    columns=["A", "B", "C", "D", "E"],
)

# 特定の列
display(df.style.background_gradient(axis=0, subset=["A", "C"]))

# 特定の行
display(df.style.background_gradient(axis=1, subset=pd.IndexSlice[["a", "c"], :]))

# 特定の範囲
display(df.style.background_gradient(axis=1, subset=pd.IndexSlice["a":"c", "A":"C"]))
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24

CSS を設定する

Advertisement

テーブルの CSS を設定する

Styler.set_table_styles() でテーブルに適用する CSS のプロパティを設定できます。

各スタイルは [{"selector": <CSS セレクタ>, "props": [(<プロパティ名>, <値>), ...]}, ...] で指定します。

In [19]:
style = df.style.set_table_styles(
    [{"selector": "tr:hover", "props": [("background-color", "yellow")]}]
)
style
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24

テーブルの属性を設定する

Styler.set_table_attributes() でテーブルに属性を設定できます。

セルの CSS を設定する

Styler.set_properties() ですべてのセルに適用する CSS のプロパティを設定できます。

In [20]:
style = df.style.set_properties(
    **{"background-color": "black", "color": "lawngreen", "border-color": "white"}
)

style
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24

行または列ごとに CSS を設定する

Styler.apply() で列または行ごとに CSS を適用できます。 引数には Series を受け取り、その Series の各要素に適用する CSS プロパティの一覧を返す関数を指定します。

In [21]:
def highlight_max(s):
    return ["background-color: green" if x == s.max() else "" for x in s]


df.style.apply(highlight_max)
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24
Advertisement

すべてのセルに CSS を設定する

Styler.apply() でセルごとに CSS を適用できます。 引数には値を受け取り、その値に適用する CSS プロパティを返す関数を指定します。

In [22]:
def highlight_even(x):
    return "background-color: green" if x % 2 == 0 else ""


df.style.applymap(highlight_even)
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24

where で条件に応じて、CSS を設定する

Styler.where(cond, value, other) は、値を引数にとり、bool を返す関数を cond に指定し、関数が True を返した場合は value を適用し、False を返した場合は other を適用します。

In [23]:
df.style.where(lambda x: x > 10, "background-color: green", "background-color: red")
A B C D E
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24

Styler.pipe() で Styler オブジェクトを引数にとり、Styler オブジェクトを返す関数を数珠つなぎで呼び出せます。

In [24]:
def set_min_max(style):
    return style.highlight_min(color="red").highlight_max(color="red")


def set_format(style):
    return style.format("{:.2f}")


df.style.pipe(set_min_max).pipe(set_format)
A B C D E
a 0.00 1.00 2.00 3.00 4.00
b 5.00 6.00 7.00 8.00 9.00
c 10.00 11.00 12.00 13.00 14.00
d 15.00 16.00 17.00 18.00 19.00
e 20.00 21.00 22.00 23.00 24.00