pandas 转置多列和重命名

dauxcl2d  于 2023-10-14  发布在  其他
关注(0)|答案(1)|浏览(128)

我有一个看起来像下面的框架:
| 产品Id|类别|月|销售|利润|
| --|--|--|--|--|
| XYX|鞋|Feb| 1000 | 1235 |
| XYX|鞋|三月| 1200 | 1455 |
| 阿坝|袋|Feb| 14000 | 7235 |
| 阿坝|袋|三月| 5200 | 8455 |
我试图半转置它-我希望每个唯一的产品ID一行,并创建新的列:feb_sales,march_sales,feb_profit,march_profit.并删除月份列。我试过用

  1. table.values.reshape(1, -1), columns=table['month','sales','Profit']

和不同版本的这一点,但我不能实现什么IM后。我希望结果是
| 产品Id|类别|二月销售额|二月份利润|三月销售|三月利润|
| --|--|--|--|--|--|
| XYX|鞋|......这是什么?|......这是什么?|||
| 阿坝|袋|......这是什么?|......|||
谢谢你的指导

g6ll5ycj

g6ll5ycj1#

试试看:

  1. # mage the Category strings consistent:
  2. df["Category"] = df["Category"].str.capitalize()
  3. # pivot the dataframe:
  4. df = df.pivot(
  5. index=["Product Id", "Category"], columns=["month"], values=["sales", "profit"]
  6. )
  7. # remove the column multi-index
  8. df.columns = [f"{b} {a}" for a, b in df.columns]
  9. # properly sort the columns:
  10. months = ["Jan", "Feb", "March", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  11. df = df[sorted(df.columns, key=lambda k: months.index(k.split()[0]))]
  12. df = df.reset_index()
  13. print(df)

图纸:

  1. Product Id Category Feb sales Feb profit March sales March profit
  2. 0 aba Bags 14000 7235 5200 8455
  3. 1 xyx Shoes 1000 1235 1200 1455
展开查看全部

相关问题