您需要通过
reset_index和参数保留索引值
id_vars:
df2 = pd.melt(df.reset_index(), id_vars='index',value_vars=['asset1','asset2'])print (df2) index variable value0 coper1 asset1 11 coper2 asset1 32 coper3 asset1 53 coper1 asset2 24 coper2 asset2 45 coper3 asset2 6
然后枢轴运行良好:
print(df2.pivot(index='index',columns = 'variable', values = 'value'))variable asset1 asset2index coper1 1 2coper2 3 4coper3 5 6
另一个可能的解决方案是
stack:
df2 = df.stack().reset_index()df2.columns = list('abc')print (df2) a b c0 coper1 asset1 11 coper1 asset2 22 coper2 asset1 33 coper2 asset2 44 coper3 asset1 55 coper3 asset2 6print(df2.pivot(index='a',columns = 'b', values = 'c'))b asset1 asset2a coper1 1 2coper2 3 4coper3 5 6
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)