如何使用Pandas自动调整转置工作簿中所有列的宽度?

问题描述

我有一本工作簿,我想自动自动调整其所有列的宽度。

以下代码有效,但仅当DataFrame未进行转置时:

for column in df:
  column_length = max(df[column].astype(str).map(len).max(),len(column))
  col_idx = df.columns.get_loc(column)
  writer.sheets['Sheet_{}'.format(i)].set_column(col_idx,col_idx,column_length)

但是,转置DataFrame时,相同的代码不起作用。有什么建议吗?

这是我目前的功能(仍在开发中):

def write_data(inventories):
    file_path = config.filepath
    file_name = config.file_name

    # log.info('Started: writing document {} on sheet {}'.format(file_name,sheet_name))
    
    dfs=[]
    for inv in inventories:
        df = pd.DataFrame(inv)

        # fix: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.
        for col in df.select_dtypes(['datetimetz']).columns:
            df[col] = df[col].dt.tz_convert(None)

        dfs.append(df)

    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('{}{}'.format(file_path,file_name),engine='xlsxwriter')
    workbook  = writer.book

    transpose = config.settings.config['excel']['transpose'].get()

    i=0
    for df in dfs:
        if transpose:
            df.transpose().to_excel(writer,sheet_name='Sheet_{}'.format(i))
            worksheet = writer.sheets['Sheet_{}'.format(i)]
            # Adjust at least the first column width
            worksheet.set_column('A:A',60)
        else:
            df.to_excel(writer,sheet_name='Sheet_{}'.format(i))
            # Adjust all columns widths
            for column in df:
                column_length = max(df[column].astype(str).map(len).max(),len(column))
                col_idx = df.columns.get_loc(column)
                writer.sheets['Sheet_{}'.format(i)].set_column(col_idx,column_length)

        i=i+1

    # Close the Pandas Excel writer and output the Excel file.
    writer.save()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)