如何重新命名和重命名pandas pivot?

时间:2017-03-20 20:46:37

标签: python python-3.x pandas

  1. 我正在尝试重新排序导出到我的Excel的列。目前按字母顺序排列。我想要销售订单净值,账单净值,然后是开放金额?
  2. 有没有办法只为excel重命名列?
  3. 如何在底部将All重命名为Grand Total
  4. enter image description here

    def create_sheet():
        scriptfile = open('script.sql', 'r')
        script = scriptfile.read()
        df2 = pd.read_sql(script, my_connection)
        df2 = df2.where((pd.notnull(df2)), None)
        pivot = pd.pivot_table(df2,
                               index=['Customer_Name'],
                               values=[
                                   'Billed_Net_Value',
                                   'Sales_Order_Net_Value',
                                   'Open_Amount'],
                               aggfunc=np.sum,
                               margins=True)
    
        writer = pd.ExcelWriter('SAP.xlsx', engine='xlsxwriter')
        pivot.to_excel(writer, sheet_name='Pivot')
        workbook = writer.book
        ws = writer.sheets['Pivot']
    

1 个答案:

答案 0 :(得分:3)

def create_sheet():
    scriptfile = open('script.sql', 'r')
    script = scriptfile.read()
    df2 = pd.read_sql(script, my_connection)
    df2 = df2.where((pd.notnull(df2)), None)
    pivot = pd.pivot_table(df2,
                           index=['Customer_Name'],
                           values=[
                               'Billed_Net_Value',
                               'Sales_Order_Net_Value',
                               'Open_Amount'],
                           aggfunc=np.sum,
                           margins=True)

    col_order = ['Sales_Order_Net_Value', 'Billed_Net_Value', 'Open_Amount']
    pivot = pivot[col_order].rename(index=dict(All='Grand Total'))

    writer = pd.ExcelWriter('SAP.xlsx', engine='xlsxwriter')
    pivot.to_excel(writer, sheet_name='Pivot')
    workbook = writer.book
    ws = writer.sheets['Pivot']