Pramod Kumar
Pramod Kumar

Reputation: 23

Wrap text for column of dataframe in pandas

I am trying to wrap text in python dataframe columns but this code is working for values in columns and not header of column.

I am using below code (taken form stackoverflow). Kindly suggest how to wrap header of dataframe

   long_text = 'aa aa ss df fff ggh ttr tre ww rr tt ww errr t ttyyy eewww rr55t e'
   data = {'a':[long_text, long_text, 'a'],'c': [long_text,long_text,long_text],
    'b':[1,2,3]}       
     df = pd.DataFrame(data)

 #choose columns of df for wrapping
 cols_for_wrap = ['a','c']


 writer = pd.ExcelWriter('aaa.xlsx', engine='xlsxwriter')
 df.to_excel(writer, sheet_name='Sheet1', index=False)

#modifyng output by style - wrap
workbook  = writer.book
 worksheet = writer.sheets['Sheet1']
 wrap_format = workbook.add_format({'text_wrap': True})
 #get positions of columns
 for col in df.columns.get_indexer(cols_for_wrap):
#map by dict to format like "A:A"     
excel_header  =  d[col] + ':' + d[col]
#None means not set with
worksheet.set_column(excel_header, None, wrap_format)
#for with = 20
worksheet.set_column(excel_header, 10, wrap_format)

writer.save()

Upvotes: 2

Views: 5996

Answers (2)

Zyxer
Zyxer

Reputation: 11

In the header_format piece that jmcnamara linked, you can add or remove any formats you want or do not want.

header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1})

# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)

My code looks like this:

h_format = workbook.add_format({'text_wrap': True})
...
...
...
for col_num, value in enumerate(df_new.columns.values):
    worksheet.write(0, col_num, value, format)
writer.save()

Upvotes: 1

jmcnamara
jmcnamara

Reputation: 41554

This is covered almost exactly in the Formatting of the Dataframe headers section of the XlsxWriter docs.

enter image description here

Upvotes: 0

Related Questions