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评论68阅读模式
英文:

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

问题

说我有一个看起来像这样的数据框

```python
商店名称 | 8/7 | 8/14 | 8/21 | 8/28 | 更多日期...
----------------------------------------------
商店1    | 2.3 | 4.5  | 6.4  | 6.5  |..
商店2    | 5.6 | 6.4  | 5.4  | 4.3  |..
商店3    | 3.4 | 5.7  | 5.3  | 7.8  |..

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

日期  | 商店   |----------------------
8/7  | 商店1 | 2.3
8/7  | 商店2 | 5.6
8/7  | 商店3 | 3.4
8/14 | 商店1 | 4.5
8/14 | 商店2 | 6.4
8/14 | 商店3 | 5.7
8/21 | 商店1 | 6.4
8/21 | 商店2 | 5.4
8/21 | 商店3 | 5.3
以此类推...

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


<details>
<summary>英文:</summary>

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..


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..


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...

</details>


# 答案1
**得分**: 0

"Wow, really simple solution actually:

```python
df.melt(id_vars='Store')
```"

<details>
<summary>英文:</summary>

Wow, really simply solution actually:

df.melt(id_vars='Store')


</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:

确定