How to wrap text for an entire column using pandas?

前端 未结 1 539
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 23:52

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 searc

1条回答
  •  滥情空心
    2021-02-16 00:12

    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()
    

    0 讨论(0)
提交回复
热议问题