gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:16:26 32 4
gpt4 key购买 nike

几天来,我一直在尝试解决 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')
如果有人可以帮我找到解决方案,这里是 Dropbox link的 excel 文档。

最佳答案

使用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
第一张:
first sheet
第二张:
second sheet

关于python - 尝试使用 sheet_name=None 为文档中的每个工作表运行 python pandas 脚本但不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68700107/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com