Search code examples
pythonpandastransform

How can I transform a table so the column headers go into the table and the table values become column headers?


How can I use pandas in Python to make this table:

data = [['4/04/2023','Floors','Tables','Roof','Paint',''],['4/05/2023','','Floors','Tables','Roof','Paint'],['4/06/2023','Paint','','Floors','Tables','Roof'],['4/07/2023','Roof','Paint','','Floors','Tables']]

df = pd.DataFrame(data, columns=['Date', 'Jim','Bob','Ed','James','Joe'])

enter image description here

Look like this? I think I have to use melt and Pivot, but I can't figure out how to get it to work. enter image description here


Solution

  • I maneged to do it, check it out:

    #let's create some initial data
    data = [['4/04/2023','Floors','Tables','Roof','Paint',''],['4/05/2023','','Floors','Tables','Roof','Paint'],['4/06/2023','Paint','','Floors','Tables','Roof'],['4/07/2023','Roof','Paint','','Floors','Tables']]
    df = pd.DataFrame(data, columns=['Date', 'Jim','Bob','Ed','James','Joe'])
    
    #apply the transformations
    df2 = df.melt(id_vars="Date", value_name='Items')
    df3 = df2.pivot(index="Date", columns='Items', values='variable')
    df3 = df3[["Floors","Tables","Roof", "Paint"]] #change the order
    

    As a result I got this:
    Result