首页 > 解决方案 > 尝试使用 sheet_name=None 为文档中的每个工作表运行 python pandas 脚本但不工作

问题描述

几天来,我一直在尝试解决我遇到的问题sheet_name=None,但是我尝试的一切都不起作用。我需要阅读一个 excel 文档并为文档中的每个工作表运行它并保留工作表的名称(而且我不知道工作表名称)。我尝试过这样的事情

dfs = pd.read_excel('products2.xlsx', sheet_name=None, index_col=[0])
for name, df in dfs.items():

但只帮助我避免了第一个错误,但它并不适用于每张纸,只适用于最后一张。

另外,在网上找到了不同的解决方案,但没有将工作表分开,我需要保留工作表和工作表名称。

import pandas as pd
import numpy as np
import seaborn as sns


df = pd.read_excel('products2.xlsx', index_col=[0], sheet_name=None)

df.columns = df.columns.str.split('_', expand=True)

new_data = df.stack(0)
new_data1 = new_data.eval('status = profit - loss + other')
new_data2 = new_data1.eval('index = (profit / status) / (loss / status)')

output = new_data2.unstack(1).swaplevel(0,1, axis=1).sort_index(axis=1)
order = output.reindex(columns=['profit', 'loss', 'other', 'status', 'index'], level=1)

rounding = order.round(3)

cm = sns.light_palette("green", as_cmap=True)
cc = sns.light_palette("red", as_cmap=True)
pc = sns.color_palette("vlag", as_cmap=True)
styler = rounding.style  # Keep Styler for reuse
green = styler.background_gradient(
    cmap=cm,
    subset=rounding.columns.get_loc_level('profit', level=1)[0]
)
red = green.background_gradient(
    cmap=cc,
    subset=rounding.columns.get_loc_level('loss', level=1)[0]
)

styler.to_excel('output_file.xlsx')

如果有人可以帮我找到解决方案,这里是Excel 文档的Dropbox 链接

标签: pythonexcelpandasdataframespreadsheet

解决方案


用于pd.ExcelWriter创建新文件并to_excel在不同的工作表上写入:

import pandas as pd
import seaborn as sns

dfs = pd.read_excel('products2.xlsx', sheet_name=None, index_col=[0])

with pd.ExcelWriter('output_file.xlsx') as writer:  # <- HERE
    for name, df in dfs.items():
        print(name)
        df.columns = df.columns.str.split('_', expand=True)
        new_data = df.stack(0)
        new_data1 = new_data.eval('status = profit - loss + other')
        new_data2 = new_data1.eval('index = (profit / status) / (loss / status)')

        output = new_data2.unstack(1).swaplevel(0,1, axis=1).sort_index(axis=1)
        order = output.reindex(columns=['profit', 'loss', 'other', 'status', 'index'], level=1)

        rounding = order.round(3)

        cm = sns.light_palette("green", as_cmap=True)
        cc = sns.light_palette("red", as_cmap=True)
        pc = sns.color_palette("vlag", as_cmap=True)
        styler = rounding.style  # Keep Styler for reuse
        green = styler.background_gradient(
            cmap=cm,
            subset=rounding.columns.get_loc_level('profit', level=1)[0]
        )
        red = green.background_gradient(
            cmap=cc,
            subset=rounding.columns.get_loc_level('loss', level=1)[0]
        )

        styler.to_excel(writer, sheet_name=name)  # <- HERE

第一张: 第一张

第二张: 第二张


推荐阅读