0
0

jupyterでpdやplのDataFrameを1行が1Lineになるようdisplayさせる(折り返し・改行抑制)

Last updated at Posted at 2024-09-11

plやpdのdfをjupyterでdisplayした際に、
日本語の自動折り返しがめちゃくちゃで行高がえらいことになって
イライラすることが度々あったので、対応関数を作成してみた。
white-space: nowrap !important; を与えることで、
セル内での改行/折り返しを抑制させている。
pandasに限れば d1.to_pandas().style.set_table_styles([{'selector': 'td', 'props': 'white-space: nowrap !important;'}]) という手もあるが、
これはpd.optionのmax_colwidthでは制御できず、
改行/折り返し無しだと横にとんでもない長さとなることがあるため却下。

from IPython.display import display_html
import pandas as pd
import polars as pl
import datetime

def display_df(df, max_strlen = 50):
    """
    plかpdのDataFrameをセル内改行を抑止してdisplayする。
   
    Args:
      df (pl.DataFrame|pd.DataFrame|dict): plかpdのDataFrame
      max_strlen (int): 表示させる最大文字数 (これ以上だと...になる)
    """
   
    tbl_id = "T_" + datetime.datetime.now().strftime("%m%d%H%M%S%f")
    new_style = '<style type="text/css">\n#' + tbl_id + ' td, th {\n  white-space: nowrap !important;\n}\n</style>'
       
    with pd.option_context("display.max_colwidth", max_strlen + 1):
        with pl.Config(fmt_str_lengths = max_strlen):
            raw_html = df._repr_html_()
           
    html_ = re.sub("<style.*?</style>", new_style, raw_html, flags = (re.MULTILINE | re.DOTALL))
    html_ = re.sub('<table', f'<table id="{tbl_id}"', html_, 1)

    display_html(html_, raw = True)  
    pass

example:

d1 = pd.DataFrame({"aa": ["aaaaaaaaaaaaaa"],
                   "bb": ["日本語の文字はうまく折り返されない。"],
                   "cc": ["aaaaaaa bbbbbbbb"], 
                   "dd": ["aaaaa bbbbbbbb cccccccc"],
                   "ee": ["aaaaaaa bbbbb cccccccc dddd"]})
display(d1)
display_df(d1)

image.png
image.png

0
0
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
0
0