大熊猫数据转换长广

muo*_*uon 2 python data-manipulation pandas

如何从这个表单中获取数据(数据的长表示):

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

print(df)
Run Code Online (Sandbox Code Playgroud)

日期:

   c0 c1  c2
0  A  b   1
2  A  c   3
3  B  d   4
Run Code Online (Sandbox Code Playgroud)

这种形式:

   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
Run Code Online (Sandbox Code Playgroud)

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

piR*_*red 5

方法1
unstackstack

df.set_index(['c0', 'c1']).unstack().stack(dropna=False).reset_index()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

方法2
reindex与产品

df.set_index(['c0', 'c1']).reindex(
    pd.MultiIndex.from_product([df.c0.unique(), df.c1.unique()], names=['c0', 'c1'])
).reset_index()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述