Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape multi-header table in python

I am new to python and trying to reshape table from excel file as I have multiple header I am trying to convert first header into 2 separate column. i am attaching my code output and data here. Input Table

import pandas as pd
import numpy as nm

df = pd.read_excel(r'.\test.xlsx', header=[0, 1])
df = (df.stack(0, dropna=False)
        .rename_axis(index=('Customer','Date'), columns=None)
        .reset_index())
df.to_csv(r'.\testnew.csv',index=False)
print(df)

Printed Output - enter image description here

Desired Output -

Customer Date Budget Actual Amount
John Jan-20 100 50 0
John Feb-20
John Mar-20
Chris Jan-20 120 80 0
Chris Feb-20 50 10 20
Chris Mar-20 50 45
like image 444
Annie Avatar asked Apr 22 '26 19:04

Annie


1 Answers

I believe you need DataFrame.stack:

df = pd.read_excel(r'.\test.xlsx', header=[0, 1])

df = (df.stack(0, dropna=False)
        .rename_axis(index=('Customer','Date'), columns=None)
        .reset_index())
like image 198
jezrael Avatar answered Apr 24 '26 08:04

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!