【问题标题】:Why this code leads to an alphabetical column list in excel?为什么此代码会导致 excel 中按字母顺序排列的列列表?
【发布时间】:2020-05-24 18:20:21
【问题描述】:
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 收益(损失)收益单位

请注意,在 Date 和 Security 列之后,即使我的代码中有 columns=[] 参数,这些列也是按字母顺序排列的。这似乎在一段时间内正常工作,然后突然恢复为“Units Proceeds ACB and Gain(Loss)”的字母顺序

任何帮助将不胜感激。

编辑:数据框中的顺序是“Account Date Security Units Proceeds ACB Gain(Loss)”,但 to_excel 过程似乎从“Units”开始按字母顺序排列。

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

【问题讨论】:

  • 显然,columns=[] 选择要写入的列,但没有定义顺序。也许您应该在导出之前重新排序 DataFrame 中的列。

标签: python excel python-3.x pandas dataframe


【解决方案1】:

我用以下方法解决了这个问题:

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)'])

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多