Pandas聚合使用pi

2024-03-29 05:40:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框如下所示:

enter image description here

我想把它转换成如下:

enter image description here

我使用以下代码:

df2_SEX_AGE=df1.pivot(index='codprg', columns=['SEX','ETA'], values='counts')

但它会引发以下错误KeyError: 'Level SEX not found'


Tags: columns数据代码ageindex错误etapivot
2条回答

要将MultiIndex转换为Index,请将列表理解与^{}一起使用以避免错误:

Index contains duplicate entries, cannot reshape


df2_SEX_AGE=df1.pivot_table(index='codprg', 
                            columns=['SEX','ETA'], 
                            values='counts',  
                            aggfunc='sum')
df2_SEX_AGE.columns = [f'{a}{b}' for a, b in df2_SEX_AGE.columns]

这会帮你解决问题:

(df1.assign(p=df['SEX'].astype(str) + df['ETA'].astype(str))
    .pivot(index='codprg', columns='p', values='counts'))

相关问题 更多 >