中分解重复的索引行?
import pandas as pd
df = pd.DataFrame({
"group": [1,2,2,3,1,2,3],
"panel": [1,1,1,1,2,2,2],
"value": [0,1,2,3,4,5,6]
})
pd.pivot_table(df, index="group", columns="panel", aggfunc="explode")
但是
"explode"
不是有效的聚合函数。我想要这个结果
value
panel 1 2
group
1 0 4
2 1 5
2 2 NaN
3 3 6
pivot
:
out = (df.assign(idx2=df.groupby(['group', 'panel']).cumcount())
.pivot(index=['group', 'idx2'], columns='panel')
)
输出:
value
panel 1 2
group idx2
1 0 0.0 4.0
2 0 1.0 5.0
1 2.0 NaN
3 0 3.0 6.0
droplevel
消除重复数据删除级别:
out = (df.assign(idx2=df.groupby(['group', 'panel']).cumcount())
.pivot(index=['group', 'idx2'], columns='panel')
.droplevel(1)
)
输出:
value
panel 1 2
group
1 0.0 4.0
2 1.0 5.0
2 2.0 NaN
3 3.0 6.0