wrap one pandas column heading and another column contents simultaneously

74 views Asked by At

I've had two styling things clash in a pandas dataframe in jupyter notebook and cancel each other out.

One column has a very long column heading, the other column has a small column heading but the cell contents are a lot of text.

I wanted to wrap the heading of the one column but contents of the other.

To reproduce:

import pandas as pd 

# create dataframe with one long column name and another column with a short name but long contents
   
d = {'one': pd.Series([10, 20, 30, 40], 
                      index=['a', 'b', 'c', 'd']), 
     'two': pd.Series(["Flexitarian palo santo JOMO next level", 
                       "disrupt tempor labore enamel pin etsy kickstarter pour-over put a bird on it adaptogen", 
                       "Kombucha whatever venmo authentic woke elit", 
                       "90s vice fingerstache est polaroid laboris iPhone taiyaki"], 
                      index=['a', 'b', 'c', 'd']),
     'Raw denim prism copper mug, cornhole poutine laborum': pd.Series([10, 20, 30, 40], 
                      index=['a', 'b', 'c', 'd'])} 
df = pd.DataFrame(d)   
df 

This creates a sample dataframe similar to what I am working with.

wrap long column heading as descriped here https://stackoverflow.com/a/43093281/4288043 :

df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])

wrap other column contents as described here https://stackoverflow.com/a/70162236/4288043 :

from IPython.display import display, HTML

def wrap_df_text(df):
    return display(HTML(df.to_html().replace("\\n","<br>")))

df['two'] = df['two'].str.wrap(20)
wrap_df_text(df)

Either of these will work separately but they will not work together.

Does anyone know how to fix it?

1

There are 1 answers

0
Timeless On BEST ANSWER

I would do it this way :

CW, HW = 25, 20 # cell's and header's width

wrap= lambda x, n: x.str.wrap(n).str.replace("\n", "<br>")

(
    df.assign(two=df["two"].pipe(wrap, CW))
        .set_axis(wrap(df.columns, HW), axis=1)
        .style
)

Output :

enter image description here