如何使用pandas将整列文字换行? [英] How to wrap text for an entire column using pandas?

查看:2666
本文介绍了如何使用pandas将整列文字换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用熊猫来包裹整列.我已经设置了列的宽度,现在我只需要包装整列,因为它们都在1行中.

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.

我搜索的答案不尽相同.我不需要编辑列的宽度,我只想将文本包装在单元格中,这与我高亮单击"Wrap Text"的列n相同.但我想使用Python脚本来完成此操作,因此我想使用熊猫来实现这一目标.

I searched with varying answers not straight to the point. I don't need to edit the width of the columns, I just want to wrap the text in the cells which does the same thing as me highlighting a column n clicking on "Wrap Text". But I want to do it using a Python script hence I would like to use pandas to achieve that.

所以基本上是

还有

但是我想通过熊猫来做到这一点,而不是通过单击自动换行来手动完成.而且我想将换行不仅应用于一个单元格,而且应用于整个列.

But I want to do this via pandas and not manually by clicking wrap text. And I want to apply the wrap to the whole column not just that one cell.

推荐答案

您可以使用解决方案修改 example_pandas_column_formats :

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

这篇关于如何使用pandas将整列文字换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆