我有一个类似的数据框
age sex values
time
2015 10 F 589628.0
2015 10 M 458390.0
2015 11 F 108018.0
2015 11 M 764350.0
....
2000 60 M 34676.0
2000 60 F 45488.0
我想像这样创建数据框
age F M
time
2015 10 589628.0 458390.0
2015 11
....
2000 60 45488.0 34676.0
将行减半并添加一列。我曾尝试使用 pivot 执行此操作,但无济于事。
df.pivot(columns='sex', values='values')
但这会返回
Index contains duplicate entries, cannot reshape
有什么想法可以在不编写繁琐的函数的情况下干净地拆分数据框吗?
干杯,迈克
最佳答案
这个我不能确定,但应该是
df.set_index(['age', 'sex'], append=True)['values'].unstack().reset_index('age')
关于python - 在 Pandas 中拆分堆叠数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39550927/