我需要一种最好的方法来拆解具有多个类别的数据框
请参见以下示例
df = pd.DataFrame(data=[['cat','tom','age',1],['cat','tom','weight',2],
['cat','jim','age',3],['cat','jim','weight',4],
['dog','max','age',1],['dog','max','weight',2],
['dog','sam','age',3],['dog','sam','weight',4]],
columns=['animal','name','param','value'])
target = pd.DataFrame(data=[['cat','tom',1,2],
['cat','jim',3,4],
['dog','max',1,2],
['dog','sam',3,4]],
columns=['animal','name','age','weight'])
# my current way
df2 = df.set_index(['animal','name','param']).unstack()
df2.columns = df2.columns.droplevel()
df2 = df2.reset_index()
做到这一点的最佳方法是什么?像通过param
列将它们分成两个数据框,然后合并回来?