【问题标题】:pandas auto adjust column width upon file open xlsxwriter?熊猫在文件打开xlsxwriter时自动调整列宽?
【发布时间】:2022-10-05 14:44:29
【问题描述】:

我有一个如下所示的熊猫数据框

df1 = pd.DataFrame({'sfassaasfsa_id': [1321352,2211252],'SUB':['Phy','Phy'],'Revasfasf_Q1':[8215215210,1221500],'Revsaffsa_Q2':[6215120,525121215125120],'Reaasfasv_Q3':[20,12],'Revfsasf_Q4':[1215120,11221252]})

我正在尝试执行以下操作

a) 根据SUB 的唯一值过滤数据帧

b) 将它们存储在多个文件中

column_name = "SUB"
col_name = "Reaasfasv_Q3"
for i,j in dict.fromkeys(zip(df1[column_name], df1[col_name])).keys():
    data_output = df1.query(f"{column_name} == @i & {col_name} == @j")
    if len(data_output) > 0:
        output_path = Path.cwd() / f"{i}_{j}_output.xlsx"
        print("output path is ", output_path)
        writer = pd.ExcelWriter(output_path, engine='xlsxwriter')
        data_output.to_excel(writer,sheet_name='results',index=False)
        for column in data_output:
            column_length = max(data_output[column].astype(str).map(len).max(), len(column))
            col_idx = data_output.columns.get_loc(column)
            writer.sheets['results'].set_column(col_idx, col_idx, column_length)
        writer.save()

虽然代码工作正常,但问题在于调整column_length

如何根据内容类型调整列长度以适合。

我希望我的输出有一个所有列都正确自动适应的 excel 文件。

虽然它可能适用于我的示例数据,但还有其他更好的方法可以使用pd.ExcelWriter 自动调整列宽吗?

【问题讨论】:

  • 你的方法是我建议的,并且在我需要在 xlsxwriter 中“自动调整”的时候成功使用。如果您尚未阅读此 SO 问题stackoverflow.com/questions/33665865/adjust-cell-width-in-excel,则有几个不同的选项。我之前尝试过 dtl85 建议的选项略有不同,但是它没有正确调整列。

标签: python excel pandas dataframe xlsxwriter


【解决方案1】:

此代码在使用时有效'openpyxl'作为您的引擎,有时pip install xlsxwriter 无法解决问题。下面的代码就像一个魅力。根据需要编辑任何部分。

def text_length(text):
    """
    Get the effective text length in characters, taking into account newlines
    """
    if not text:
        return 0
    lines = text.split("
")
    return max(len(line) for line in lines)

def _to_str_for_length(v, decimals=3):
    """
    Like str() but rounds decimals to predefined length
    """
    if isinstance(v, float):
        # Round to [decimal] places
        return str(Decimal(v).quantize(Decimal('1.' + '0' * decimals)).normalize())
    else:
        return str(v)


def auto_adjust_xlsx_column_width(df, writer, sheet_name, margin=3, length_factor=1.0, decimals=3, index=False):

    sheet = writer.sheets[sheet_name]
    _to_str = functools.partial(_to_str_for_length, decimals=decimals)
    # Compute & set column width for each column
    for column_name in df.columns:
        # Convert the value of the columns to string and select the 
        column_length =  max(df[column_name].apply(_to_str).map(text_length).max(), text_length(column_name)) + 5
        # Get index of column in XLSX
        # Column index is +1 if we also export the index column
        col_idx = df.columns.get_loc(column_name)
        if index:
            col_idx += 1
        # Set width of column to (column_length + margin)
        sheet.column_dimensions[openpyxl.utils.cell.get_column_letter(col_idx + 1)].width = column_length * length_factor + margin
    # Compute column width of index column (if enabled)
    if index: # If the index column is being exported
        index_length =  max(df.index.map(_to_str).map(text_length).max(), text_length(df.index.name))
        sheet.column_dimensions["A"].width = index_length * length_factor + margin

使用示例

with pd.ExcelWriter('report.xlsx', sheet_name="results", engine='openpyxl') as writer:
    report_df.to_excel(writer,index=False, sheet_name="results")
    auto_adjust_xlsx_column_width(report_df, writer, "results")

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2023-03-11
    • 2016-01-21
    • 2023-03-29
    • 2013-05-21
    相关资源
    最近更新 更多