我在 pandas 数据框中有几列包含长文本字符串的列,但我只对检查其中一列感兴趣。有没有办法按照
pd.set_option('max_colwidth', 60)
的方式使用某些东西,但仅适用于 单列,而不是扩展我的 df 中所有列的宽度?
我在较新版本的 Pandas 上找到的最简单的解决方案在 Pandas 参考材料的此页中概述。搜索
display.max_colwidth
——页面下方大约 1/3 描述了如何使用它,例如:
pd.set_option('max_colwidth', 400)
请注意,这将为会话设置值,或直到更改为止。
如果您只想进行临时更改,请参阅此信息有关临时设置上下文的信息,例如:
from pandas import option_context
with option_context('display.max_colwidth', 400):
display(df.head())
我还没有找到一种明显的方法来设置各个列,但这种方法只会将那些需要更多空间的列扩大到您设置的最大值。
如果尝试调整如何适应屏幕/表格/为其他列留出空间,也可能有用的是
pd.set_option('precision', 2)
,它会改变小数位数。
如果您想更改 Jupyter Notebook 中的显示,可以使用 Style 功能。 要仅对某些列使用此格式,只需通过
subset
参数指示要放大的列即可。这基本上是 HTML 和 CSS。
### Test data
df = DataFrame({'text': ['foo foo foo foo foo foo foo foo', 'bar bar bar bar bar'],
'number': [1, 2]})
df.style.set_properties(subset=['text'], **{'width': '300px'})
涉及
pd.set_option('max_colwidth', 400)
的答案对我不起作用。
但是
Dataframe.style.set_table_styles()
对我有用。了解这一点很棒,因为我们可以用它做很多事情。
例如:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(4, 4),
columns=['A', 'B', 'C', 'D'])
现在,让我们用
A
更改 Column df.style.set_table_styles()
的宽度。
df.style.set_table_styles({
'A': [{'selector': '',
'props': [('width', '200px')]}],
}, overwrite=False)
现在,让我们做更多的事情:
df.style.set_table_styles({
'A': [{'selector': '',
'props': [('color', 'red'), ('width', '200px')]}],
'B': [{'selector': 'td',
'props': [('color', 'blue')]}]
}, overwrite=False)
我们甚至可以对多索引数据框做这种事情。
import numpy as np
df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]],
index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'),
columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:']))
df
然后更改表属性
df.style.set_table_styles({
('Regression', 'Tumour'): [{'selector': '',
'props': [('background-color', '#00aaaa')]},
],
('Regression', 'Non-Tumour'): [{'selector': '',
'props': [('background-color', '#00aaff'), ('width', '200px')]},
]
}, axis=0)
我们还可以玩行。
df.style.set_table_styles([{'selector': 'tr',
'props': [('line-height', '40px')]},
], axis=1)
这对我有用:
请记住,将 payload 替换为您的数据。
payload = {'col1': 'col1', 'col2': 'col2'}
df = pd.DataFrame(payload)
response = HttpResponse(content_type='application/xlsx')
response['Content-Disposition'] = f'attachment; filename="{filename}.xlsx"'
with pd.ExcelWriter(response) as writer:
df.to_excel(writer, sheet_name=f'worksheet_name', index=False)
# Manually adjust the width of column
for column in df:
column_width = max(df[column].astype(str).map(len).max(), len(column))
col_idx = df.columns.get_loc(column)
writer.sheets[f'worksheet_name'].set_column(col_idx, col_idx, column_width)
return response