重组多级索引的数据框架。

huangapple go评论109阅读模式
英文:

How to restructure multi-index dataframe

问题

以下是翻译好的部分:

我有一个包含财务数据的数据框,看起来像这样:

  1. Y0 Y1 Y2 Y3
  2. Variable1 Company1 0 2 4 5
  3. Company2 0 2 4 5
  4. Company3 0 2 4 5
  5. Variable2 Company1 0 2 4 5
  6. Company2 0 2 4 5
  7. Company3 0 2 4 5

是否有一种方法可以重新构造数据框,使其看起来像这样:

  1. Variable1 Variable2
  2. Company1 Y0 0 0
  3. Y1 1 1
  4. Y2 2 2
  5. ...
  6. Company2 Y0 0 0
  7. Y1 1 1
  8. Y2 2 2

我尝试重新排序级别,但它没有给出我想要的结果,因为标签位于不同的轴上。

英文:

I have a dataframe with financial data, which looks like following:

  1. Y0 Y1 Y2 Y3
  2. Variable1 Company1 0 2 4 5
  3. Company2 0 2 4 5
  4. Company3 0 2 4 5
  5. Variable2 Company1 0 2 4 5
  6. Company2 0 2 4 5
  7. Company3 0 2 4 5

Is there a way to restructure the dataframe so it looks like this:

  1. Variable1 Variable2
  2. Company1 Y0 0 0
  3. Y1 1 1
  4. Y2 2 2
  5. ...
  6. Company2 Y0 0 0
  7. Y1 1 1
  8. Y2 2 2

I have tried to reorder levels, but it doesn't give the result i want, since the lables are on different axis.

data

答案1

得分: 5

Use:

  1. df.stack().unstack(0)
  2. 输出:
  3. 变量1 变量2
  4. 公司1 Y0 0 0
  5. Y1 2 2
  6. Y2 4 4
  7. Y3 5 5
  8. 公司2 Y0 0 0
  9. Y1 2 2
  10. Y2 4 4
  11. Y3 5 5
  12. 公司3 Y0 0 0
  13. Y1 2 2
  14. Y2 4 4
  15. Y3 5 5
英文:

Use:

  1. df.stack().unstack(0)

OUtput:

  1. Variable1 Variable2
  2. Company1 Y0 0 0
  3. Y1 2 2
  4. Y2 4 4
  5. Y3 5 5
  6. Company2 Y0 0 0
  7. Y1 2 2
  8. Y2 4 4
  9. Y3 5 5
  10. Company3 Y0 0 0
  11. Y1 2 2
  12. Y2 4 4
  13. Y3 5 5

huangapple
  • 本文由 发表于 2020年1月6日 21:56:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定