pandas ,融化,未融化保存指数 [英] pandas, melt, unmelt preserve index

查看:89
本文介绍了 pandas ,融化,未融化保存指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张客户(资产)和资产分配(资产)表

I've got a table of clients (coper) and asset allocation (asset)

A = [[1,2],[3,4],[5,6]]
idx = ['coper1','coper2','coper3']
cols = ['asset1','asset2']

df = pd.DataFrame(A,index = idx, columns = cols)

所以我的数据看起来像

        asset1  asset2
coper1       1       2
coper2       3       4
coper3       5       6

,我想通过线性优化来运行它们(我有约束-像sum of all of asset_i <= amount_on_hand_isum of coper_j = price_j一样)

and I want to run them through a linear optimization (i've got constraints- somtehing like sum of all of asset_i <= amount_on_hand_i and sum of coper_j = price_j)

所以我必须将2D矩阵转换为1D向量.融化很容易

so I have to turn this 2D matrix into a 1D vector. Which is easy with melt

df2 = pd.melt(df,value_vars=['asset1','asset2'])

但是现在,当我尝试解开它时,我得到了一个6行数组,其中有很多空白!

But now, when I try to unmelt it, I get a 6-row array with lots of blanks!

df2.pivot(columns = 'variable', values = 'value')


variable  asset1  asset2
0            1.0     NaN
1            3.0     NaN
2            5.0     NaN
3            NaN     2.0
4            NaN     4.0
5            NaN     6.0

在使用melt时,有什么方法可以保留索引的"coper"部分吗?

Is there any way to preserve the 'coper' part of my indexing while using melt?

推荐答案

您需要通过然后枢轴运行良好:

print(df2.pivot(index='index',columns = 'variable', values = 'value'))
variable  asset1  asset2
index                   
coper1         1       2
coper2         3       4
coper3         5       6

使用 stack :

Another possible solution with stack:

df2 = df.stack().reset_index()
df2.columns = list('abc')
print (df2)
        a       b  c
0  coper1  asset1  1
1  coper1  asset2  2
2  coper2  asset1  3
3  coper2  asset2  4
4  coper3  asset1  5
5  coper3  asset2  6

print(df2.pivot(index='a',columns = 'b', values = 'c'))
b       asset1  asset2
a                     
coper1       1       2
coper2       3       4
coper3       5       6

这篇关于 pandas ,融化,未融化保存指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆