pandas 如何转换表,使列标题进入表,表值成为列标题?

oipij1gg  于 2023-04-19  发布在  其他
关注(0)|答案(2)|浏览(147)

如何在Python中使用pandas来创建这个表:
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'])

看起来像这样?我想我必须使用melt和Pivot,但我不知道如何让它工作。

elcex8rz

elcex8rz1#

我已经做了,看看吧:

#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

结果我得到了这个:

643ylb08

643ylb082#

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

结果

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

相关问题