大熊猫数据转换长广

时间:2016-12-16 16:13:07

标签: python pandas data-manipulation

如何从此表单获取数据(数据的长表示):

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

长期从长到长的转型是这样做的唯一方法吗?

1 个答案:

答案 0 :(得分: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

相关问题