创建一个多级列数据透视表在 pandas 中。

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

Create a multi-level column pivot table in pandas

问题

你可以使用Python创建类似下面的多级列透视表:

从这个数据框开始:

  1. | Date | Name | P&L | Percentage |
  2. |2023.1.1 | Amy |1.1% | 2% |
  3. | 2023.1.1 | Peter |1.2% | 3% |

生成如下透视表:

  1. | Date | Amy | Peter |
  2. | | P&L | Percentage | P&L | Percentage |
  3. |2023.1.1 | 1.1%| 2% |1.2% | 3% |

以下是代码示例,可以帮助你创建这种多级列透视表:

  1. import pandas as pd
  2. # 创建数据框
  3. data = {
  4. 'Date': ['2023.1.1', '2023.1.1'],
  5. 'Name': ['Amy', 'Peter'],
  6. 'P&L': ['1.1%', '1.2%'],
  7. 'Percentage': ['2%', '3%']
  8. }
  9. df = pd.DataFrame(data)
  10. # 使用pivot方法创建透视表
  11. result = df.pivot(index='Date', columns='Name', values=['P&L', 'Percentage'])
  12. # 重新设置列的多级索引
  13. result.columns = result.columns.map(lambda x: f'{x[1]}_{x[0]}')
  14. # 重置列索引
  15. result.reset_index(inplace=True)
  16. # 输出透视表
  17. print(result)

这将生成所需的多级列透视表。

英文:

How can I create the multi-level column pivot table like below using python?
创建一个多级列数据透视表在 pandas 中。

from this data frame

  1. | Date | Name | P&L | Percentage |
  2. |2023.1.1 | Amy |1.1% | 2% |
  3. | 2023.1.1 | Peter |1.2% | 3% |

To pivot table like this

  1. | Date | Amy | Peter |
  2. | | P&L |Percentage | P&L |Percentage |
  3. |2023.1.1 | 1.1%| 2% |1.2% | 3% |

This is my previous code and seems doesn't work
result=df.pivot_table(index='Date',values=['P&L','Percentage'],columns='Name')

答案1

得分: 1

使用 pivot 在这里,因为你没有数值数据:

  1. df.pivot(index='Date', values=['P&L','Percentage'], columns='Name')

或者使用带有 aggfunc='first'pivot_table:

  1. df.pivot_table(index='Date', values=['P&L','Percentage'], columns='Name', aggfunc='first')

输出:

  1. P&L Percentage
  2. Name Amy Peter Amy Peter
  3. Date
  4. 2023.1.1 1.1% 1.2% 2% 3%
英文:

Use pivot here as you don't have numeric data:

  1. df.pivot(index='Date',values=['P&L','Percentage'],columns='Name')

Or pivot_table with aggfunc='first':

  1. df.pivot_table(index='Date',values=['P&L','Percentage'],columns='Name',aggfunc='first')

Output:

  1. P&L Percentage
  2. Name Amy Peter Amy Peter
  3. Date
  4. 2023.1.1 1.1% 1.2% 2% 3%

huangapple
  • 本文由 发表于 2023年2月16日 02:51:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464252.html
匿名

发表评论

匿名网友

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

确定