2

Trying to break long lines on ';' (semicolon) AND left align the output of that column

# Python version 3.9.12.final.0
import pandas as pd  # Pandas version 1.4.2
import numpy as np
from tabulate import tabulate
from IPython.display import HTML
    
# initialize list elements
long_field_data = [
    [10, "1_super_long_data textA textB textC;2_super_long_data textD textE textF;3_super_long_data textnothing"],
    [101, "2_super_long_data textA textB textJ;2_super_long_data textK textL textM;3_super_long_data textMoreNothing"],
    [1002, "3_super_long_data textA textB textW;2_super_long_data textX textY textZ;3_super_long_data LessThanNothing"],
]
        
# Create the pandas DataFrame
df_test = pd.DataFrame(long_field_data, columns=['cNameOne', 'Test Sequence'])
    
pd.set_option('display.max_colwidth', None)
    
df_test

to get: Raw Data output visually

I can break those lines on the semicolons:

display(HTML(df_test.to_html().replace(";","<br>")))

to get:

enter image description here

But, I can't get them left-aligned. Tried:

style.set_properties(**{'text-align': 'left'})         #FAILS

tabulate(df, showindex=False, headers=df.columns)     #FAILS (and not HTML, of course)

# various forms of:
df['Test Sequence'] = df['Test Sequence'].str.ljust(0)     # ALL FAIL

and many other pretty_print() functions, etc... All FAIL

IS IT POSSIBLE to get HTML output (or even textual output like Tabulate) with this column / series left-aligned?

Laurent
  • 12,287
  • 7
  • 21
  • 37
Andrew Ward
  • 171
  • 2
  • 13

1 Answers1

1

Here is one way to do it:

df_test["Test Sequence"] = df_test["Test Sequence"].str.replace(";", "<br>")

styles = [
    {"selector": "td", "props": [("text-align", "left")]}
]
df_test.style.set_table_styles(styles)

Output in a Jupyter notebook:

enter image description here

Laurent
  • 12,287
  • 7
  • 21
  • 37