在Python中重复旋转多个列

2024-05-19 01:47:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个框架中有如下数据:

Region   Date   Drip Coffee  Espresso  Latte  Other
Central   1         5           1        2      3
East      1         3           3        1      4
North     1         5           1        3      2
Central   2         2           7        2      0
East      2         10          3        2      1
North     2         6           9        4      2
.
.
.

我想把咖啡、意式浓缩咖啡、拿铁咖啡和其他咖啡放在一起,这样它就可以在日期和地区重复排列,比如:

Region   Date      Type       Value
Central   1      Drip Coffee    5      
East      1      Drip Coffee    3             
North     1      Drip Coffee    5    
Central   1       Espresso      1      
East      1       Espresso      3       
North     1       Espresso      1       
.
.
.
Central   2      Drip Coffee    2      
East      2      Drip Coffee    10             
North     2      Drip Coffee    6    
.
.

我试过一些方法,比如:

df_new = df_old.pivot(index='Date',columns=['Drip Coffee', 'Espresso', 'Latte', 'Other']).stack(0).rename_axis(['Date','Type']).reset_index()

但这给了我ValueError: all arrays must be same length

我知道在我的Value测试中缺少了一个新的列,但这是因为我不知道如何像这样透视一系列值

我想看看是否有一个可能的解决办法,因为这个问题似乎是非常独特的;我找不到这样一个多重重复的解决方案


Tags: dfdateindexvaluetyperegioncoffeecentral
1条回答
网友
1楼 · 发布于 2024-05-19 01:47:11

设置

d = {'id_vars': ['Region', 'Date'], 'var_name': 'Type', 'value_name': 'Value'}

IIUC,使用meltsort_values

df.melt(**d).sort_values(by=['Date', 'Type'])

     Region  Date         Type  Value
0   Central     1  Drip Coffee      5
1      East     1  Drip Coffee      3
2     North     1  Drip Coffee      5
6   Central     1     Espresso      1
7      East     1     Espresso      3
8     North     1     Espresso      1
12  Central     1        Latte      2
13     East     1        Latte      1
14    North     1        Latte      3
18  Central     1        Other      3
19     East     1        Other      4
20    North     1        Other      2
3   Central     2  Drip Coffee      2
4      East     2  Drip Coffee     10
5     North     2  Drip Coffee      6
9   Central     2     Espresso      7
10     East     2     Espresso      3
11    North     2     Espresso      9
15  Central     2        Latte      2
16     East     2        Latte      2
17    North     2        Latte      4
21  Central     2        Other      0
22     East     2        Other      1
23    North     2        Other      2

相关问题 更多 >

    热门问题