Issue
I want to use Pandas, to wrap an entire column. I have already set the width for the columns now I just need to wrap the entire column as they are all in 1 line.
I do not need to edit the width of the columns, I want to wrap the text in the cells.
I can do this in Excel by clicking on "Wrap Text", see example below:
Desired output:
How can I apply wrapping on a column with Pandas and not manually in Excel ?
Solution
You can use solution modifying example_pandas_column_formats:
import string
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})
#dictionary for map position of selected columns to excel headers
d = dict(zip(range(26), list(string.ascii_uppercase)))
print (d)
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I',
9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q',
17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}
#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, 20, wrap_format)
writer.save()
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.