在Pandas中旋转数据框。

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

Pivot dataframe in Pandas

问题

Week Parameter Total
1 Sales 34
1 Revenue 56
2 Sales 42
2 Revenue 57
3 Sales 20
3 Revenue 6
英文:

Current df:

Week Sales Revenue
1 34 56
2 42 57
3 20 6

I am trying to get the following structure:

Week Parameter Total
1 Sales 34
1 Revenue 56
2 Sales 42
2 Revenue 57
3 Sales 20
3 Revenue 6

I have tried the following but I 'values' only accepts one column.

pivot = pd.pivot_table(df1, values = 'Sales', index=['Week','Revenue'], columns = 'Week').reset_index

答案1

得分: 3

只需使用 melt,这是 pivot 的反向操作。

https://pandas.pydata.org/docs/user_guide/reshaping.html#reshaping-by-melt

df1.melt(id_vars=["Week"], var_name="Parameter", value_name="Total")

请注意,stack 也执行类似的操作(而 unstack 类似于 pivot)。但是,stack/unstack 完全依赖于(多重)索引来理解您希望执行的操作,而 melt/pivot 更具可配置性。

英文:

Just use melt, the inverse operation of pivot.

https://pandas.pydata.org/docs/user_guide/reshaping.html#reshaping-by-melt

df1.melt(id_vars=["Week"], var_name="Parameter", value_name="Total")

Note that stack is also doing a similar operation (and unstack is similar to pivot). But stack/unstack solely rely on (multi)index to understand what you wish to do, while melt/pivot are more configurable

答案2

得分: 2

另一种可能的解决方案:

(df.set_index('Week').stack().reset_index()
 .set_axis(['Week', 'Parameter', 'Total'], axis=1))

或者,

(df.set_index('Week').stack().rename('Total').to_frame()
 .reset_index(names=['Week', 'Parameter']))

输出:

   Week Parameter  Total
0     1     Sales     34
1     1   Revenue     56
2     2     Sales     42
3     2   Revenue     57
4     3     Sales     20
5     3   Revenue      6
英文:

Another possible solution:

(df.set_index('Week').stack().reset_index()
 .set_axis(['Week', 'Parameter', 'Total'], axis=1))

Alternatively,

(df.set_index('Week').stack().rename('Total').to_frame()
 .reset_index(names=['Week', 'Parameter'])) 

Output:

   Week Parameter  Total
0     1     Sales     34
1     1   Revenue     56
2     2     Sales     42
3     2   Revenue     57
4     3     Sales     20
5     3   Revenue      6

huangapple
  • 本文由 发表于 2023年6月8日 03:08:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426388.html
匿名

发表评论

匿名网友

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

确定