4
6

More than 3 years have passed since last update.

Flask入門その2:データフレームをスタイルシートで見栄えよく表示

Last updated at Posted at 2019-11-17

環境

Mac、ローカル

おしゃれなスタイルシートを拾ってきてそのまま適用できないかと目論んだが、だめだった

http://www.htmlandcssbook.com/extras/table-styles/
image.png

なぜか?このスタイルシートが想定している構造(例えば下図)と
image.png

pd.DataFrame.to_html()で吐き出される構造とは違うからでる

to_html()で吐き出される構造とJupyterっぽく表示できるところまで

非常に分かりやすいのがあった。まじでここに全部書いてあるのでコード掲載等は割愛
https://stackoverflow.com/questions/50807744/apply-css-class-to-pandas-dataframe-using-to-html
image.png

ちなみにスタイルシートを変更したのに反映されてないぞ?と思ったら
127.0.0.1:5000/static/style.css
変更が確認できるまで何度か読み込んでからアクセスすると、反映される場合がある

上記参考に、cssを書き換えてちょいおしゃれにする

頑張ってこんな感じにした
image.png

app.py

from flask import Flask,render_template,url_for
import seaborn as sns
app = Flask(__name__)

@app.route('/')
def index():
    df = sns.load_dataset('iris')
    return render_template('index.html', 
                            table=(df
                                .head(15)
                                .to_html(classes="mystyle"))
                            )

if __name__ == "__main__":
    app.run()

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>mystyle</title>
    <link rel="stylesheet" 
        type="text/css"
        href="{{url_for('static', filename='style.css')}}">
    <style type="text/css">
        body {
                font-family: Arial, Verdana, sans-serif;
                font-size: 90%;
                color: #666;
                background-color: #f8f8f8;}
        </style>
</head>
<body>
        <h1>iris data table</h1>    
        {{table | safe}}
</body>
</html>

style.css

mystyle {
    border-spacing: 0px;
    border-top: 0px solid;
    border-left: 0px solid;
    border-right: 0px solid;
    border-bottom: 0px solid;
}

.mystyle th, td {
    border-spacing: 0px;
    padding: 5px;
    border-top: 1px solid #f1f8fe;
    border-bottom: 1px solid #cbd2d8;
    border-right: 1px solid #cbd2d8;
    margin: 0px;
}

.mystyle thead, th:first-child {
    background-color: #90b4d6;
    text-shadow: -1px -1px 1px #666666;
}

.mystyle thead th{
    color:white;
    text-align: center;
    border-bottom: 2px solid #547ca0;
    letter-spacing: 0.15em;
}
.mystyle th:first-child {
    color:white;
    text-align: right;
}

.mystyle td {
    text-align: right;
}

.mystyle tr:nth-child(even) {
    background: #E0E0E0;
}

.mystyle thead tr th:first-child {
    -webkit-border-top-left-radius: 5px;
    -moz-border-radius-topleft: 5px;
    border-top-left-radius: 5px;}

.mystyle thead tr th:last-child {
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius-topright: 5px;
    border-top-right-radius: 5px;}    

※style sheetはあんまり理解してない。無駄が多いと思う

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6