2016-12-16 145 views
2

如何从这种形式获得的数据(数据长表示):大熊猫数据转换长宽长

import pandas as pd 
df = pd.DataFrame({ 
    'c0': ['A','A','B'], 
    'c1': ['b','c','d'], 
    'c2': [1, 3,4]}) 

print(df) 

日期:

c0 c1 c2 
0 A b 1 
2 A c 3 
3 B d 4 

这种形式:

c0 c1 c2 
0 A b 1 
2 A c 3 
3 A d NaN 
4 B b NaN 
5 B c NaN 
6 B d 4 

长久以来一直以广泛的长期转型来做到这一点的唯一方法?

回答

5

方法1
unstackstack

df.set_index(['c0', 'c1']).unstack().stack(dropna=False).reset_index() 

enter image description here

方法2
reindex与产品

df.set_index(['c0', 'c1']).reindex(
    pd.MultiIndex.from_product([df.c0.unique(), df.c1.unique()], names=['c0', 'c1']) 
).reset_index() 

enter image description here

+0

set_index会做C0的笛卡尔积,C1? – MYGz

+0

@MohammadYusufGhazi no! 'unstack'会。 – piRSquared

+0

@piRSquared谢谢,我正在更新我的问题以添加多个值列,这在使用'pandas.melt''时似乎是个问题,但您的方法很好解决了这个问题 – muon