如何使用 Pandas 为整列换行文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45985358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to wrap text for an entire column using pandas?
提问by Uraforclain
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.
我想使用Pandas来包装整列。我已经设置了列的宽度,现在我只需要将整列包裹起来,因为它们都在 1 行中。
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.
我搜索了不同的答案,但并不直截了当。我不需要编辑列的宽度,我只想将文本包裹在单元格中,这与我在单击“包裹文本”时突出显示列 n 的作用相同。但是我想使用 Python 脚本来完成它,因此我想使用 Pandas 来实现这一点。
So basically the
所以基本上
And the
而
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.
但我想通过Pandas来做到这一点,而不是通过单击换行来手动完成。而且我想将换行应用到整个列,而不仅仅是那个单元格。
回答by jezrael
You can use solution modifying example_pandas_column_formats:
您可以使用修改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()