为什么此代码会导致 excel 中按字母顺序排列的列列表?


table = pd.pivot_table(gains,
index=['Account', 'Date', 'Security'],
values=['Units', 'Proceeds', 'ACB', 'Gain(Loss)'])
# pivot table for gains(losses) broken down by investment account
for account in table.index.get_level_values(0).unique():
# print gains losses sheets one summary for each investment account
temp_df = table.xs(account, level=0)
# column_titles = ['Units', 'Proceeds', 'ACB', 'Gain(Loss)']
# temp_df.reindex(columns=column_titles)
s_name = account + ' - ' + str(idate.year)
temp_df.to_excel(writer, sheet_name=s_name,
columns=['Units', 'Proceeds', 'ACB', 'Gain(Loss)'])

第一个 Excel 工作表显示了增益数据帧的列的正确顺序:

即账户日期 证券单位收益 ACB 收益(亏损(

但是,各个 temp.df 数据帧会按以下列顺序创建 Excel 工作表:

即日期证券 ACB 收益(亏损(收益单位

请注意,在"日期"和"安全性"列之后,即使我的代码中有 columns=[] 参数,这些列也按字母顺序排列。这似乎在一段时间内正常工作,突然恢复为"单位收益ACB和收益(损失("的字母顺序

任何帮助将不胜感激。

编辑:数据帧中的顺序是"帐户日期安全单位收益ACB收益(损失(",但to_excel程序似乎从各个工作表的"单位"开始按字母顺序排列。

Edit2:或者,按照我想要的顺序获取这些列的最佳方法是什么。我应该使用 openpyxl、xlrd、xlwt 还是我想要的真的不可能?

我用以下内容解决了这个问题:

s_name = account + ' - ' + str(idate.year)
temp_df = temp_df[['Units', 'Proceeds', 'ACB', 'Gain(Loss)']]
temp_df.to_excel(writer, sheet_name=s_name,
columns=['Units', 'Proceeds', 'ACB', 'Gain(Loss)'])

最新更新