尝试为文档中的每个 sheet 运行 python pandas 脚本 sheet_name=None 但不工作

Trying to run python pandas script for every sheet in document with sheet_name=None but not working

几天来,我一直在尝试解决 sheet_name=None 遇到的问题,但是我尝试的所有方法都不起作用。我需要阅读 excel 文档和 运行 文档中的每个 sheet 并保留 sheet 的名称(我不知道 sheet 名称).我试过这样的东西

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

但只帮助我避免了第一个错误,但它不会 运行 每个 sheet,只有最后一个。

另外,在网上找到了不同的解决方案,但没有保持 sheet 分开,我需要保持 sheets 和 sheetnames.

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 link

使用pd.ExcelWriter创建新文件,to_excel写入不同的sheet:

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

首先sheet:

第二个sheet: