python - 尝试使用 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 链接。
解决方案
用于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
推荐阅读
- regex - 正则表达式 - Linux - 介于,但不包括
- python - 如何展平python中列表列表的一层?
- php - 使用管理路由时,CakePHP 3 无法生成正确的 URL
- python-3.x - 问题表明scrapy中的HashedControlPassword错误,而它正是torrc文件中出现的那个
- python - 我不确定如何实现我的二维数组
- regex - 如何在记事本++中使用正则表达式替换字符串的一部分
- angular - 在没有 SystemJS 的情况下将参数传递给 Angular7 应用程序
- asp.net-core-signalr - 为什么客户端方法在 siganlR 中调用了 4 次?
- sapui5 - 如何在 SAPUI5 的 XML 视图中的另一个绑定中进行绑定?
- mysql - MySql - 如何将存储的函数存储在表中?