英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论