How do I melt and/or pivot my pandas dataframe in way that forces x-axis titles to become index? (see description for visual)

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

How do I melt and/or pivot my pandas dataframe in way that forces x-axis titles to become index? (see description for visual)

问题

  1. 说我有一个看起来像这样的数据框
  2. ```python
  3. 商店名称 | 8/7 | 8/14 | 8/21 | 8/28 | 更多日期...
  4. ----------------------------------------------
  5. 商店1 | 2.3 | 4.5 | 6.4 | 6.5 |..
  6. 商店2 | 5.6 | 6.4 | 5.4 | 4.3 |..
  7. 商店3 | 3.4 | 5.7 | 5.3 | 7.8 |..

但我想让我的数据框看起来像这样:

  1. 日期 | 商店 |
  2. ----------------------
  3. 8/7 | 商店1 | 2.3
  4. 8/7 | 商店2 | 5.6
  5. 8/7 | 商店3 | 3.4
  6. 8/14 | 商店1 | 4.5
  7. 8/14 | 商店2 | 6.4
  8. 8/14 | 商店3 | 5.7
  9. 8/21 | 商店1 | 6.4
  10. 8/21 | 商店2 | 5.4
  11. 8/21 | 商店3 | 5.3
  12. 以此类推...

我该如何在 pandas 中实现这个?我猜这是 pandas 中的 melt 函数,但我对这个有些难以理解...

  1. <details>
  2. <summary>英文:</summary>
  3. Say I have a df that looks like this:

Store Name | 8/7 | 8/14 | 8/21 | 8/28 | more dates...

Store 1 | 2.3 | 4.5 | 6.4 | 6.5 | Value..
Store 2 | 5.6 | 6.4 | 5.4 | 4.3 | Value..
Store 3 | 3.4 | 5.7 | 5.3 | 7.8 | Value..

  1. But I want my df to look like this:

Date | Store | Value

8/7 |Store 1| 2.3
8/7 |Store 2| 5.6
8/7 |Store 3| 3.4
8/14 |Store 1| 4.5
8/14 |Store 2| 6.4
8/14 |Store 3| 5.7
8/21 |Store 1| 6.4
8/21 |Store 2| 5.4
8/21 |Store 3| 5.3
etc..

  1. How do I do this with pandas? I&#39;m assuming this is a melt function of pandas, but I&#39;m struggling to wrap my head around this one...
  2. </details>
  3. # 答案1
  4. **得分**: 0
  5. "Wow, really simple solution actually:
  6. ```python
  7. df.melt(id_vars='Store')
  8. ```"
  9. <details>
  10. <summary>英文:</summary>
  11. Wow, really simply solution actually:

df.melt(id_vars='Store')

  1. </details>

huangapple
  • 本文由 发表于 2023年6月30日 02:48:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583860.html
匿名

发表评论

匿名网友

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

确定