pandas数据转换长-宽-长

pandas data transformation long-wide-long

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

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

从长到宽到长的转换是唯一的方法吗?

方法一
unstackstack

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

方法二
reindex 与产品

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