2024-03-29 05:40:56 发布
网友
我的数据框如下所示:
我想把它转换成如下:
我使用以下代码:
df2_SEX_AGE=df1.pivot(index='codprg', columns=['SEX','ETA'], values='counts')
但它会引发以下错误KeyError: 'Level SEX not found'
KeyError: 'Level SEX not found'
要将MultiIndex转换为Index,请将列表理解与^{}一起使用以避免错误:
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'))
要将} 一起使用以避免错误:
MultiIndex
转换为Index
,请将列表理解与^{这会帮你解决问题:
相关问题 更多 >
编程相关推荐