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

Question:

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

Asked By: James C

||

Answers:

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

import pandas as pd

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

dct = [{v:k for k,v in d.items()} 
for d in df[['Jim','Bob','Ed','James','Joe']].to_dict(orient='records')]

r = pd.DataFrame.from_dict(dct).drop(columns='')
r['Date'] = df['Date']

print(r[['Date', 'Floors','Tables','Roof','Paint']])

Result

        Date Floors Tables   Roof  Paint
0  4/04/2023    Jim    Bob     Ed  James
1  4/05/2023    Bob     Ed  James    Joe
2  4/06/2023     Ed  James    Joe    Jim
3  4/07/2023  James    Joe    Jim    Bob
Answered By: Laurent B.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.