将多列更改为在 python 中具有三个单独列的行

Change multiple columns into rows having three separate columns in python

样本来源Table

城市 2010 年第一季度交货 2010 年第二季度交货 2010 年第三季度交货 2010 年第 4 季度交货 2010Q1服务 2010Q2服务 2010 年第 3 季度的服务 2010 年第 4 季度的服务
一个 10 15 20 25 20 25 30 35
B 30 30 40 55 20 25 45 55
C 20 25 40 55 25 35 40 65

结果Table

城市 期间 交货 服务
一个 2010Q1 10 20
一个 2010Q2 15 25
一个 2010Q3 20 30
一个 2010Q4 25 35
B 2010Q1 30 20
B 2010Q2 30 25
B 2010Q3 40 45
B 2010Q4 55 55
C 2010Q1 20 25
C 2010Q2 25 35
C 2010Q3 40 40
C 2010Q4 55 65

我使用了 melt 函数,但无法获得所需的输出。

使用wide_to_long:

df = (pd.wide_to_long(df, 
                     stubnames=['Delivery in ','Services in '], 
                     i='City', 
                     j='Period', 
                     suffix='\w+')
        .rename(columns=lambda x: x.split()[0])
        .sort_index()
        .reset_index())
print (df)
   City  Period  Delivery  Services
0     A  2010Q1        10        20
1     A  2010Q2        15        25
2     A  2010Q3        20        30
3     A  2010Q4        25        35
4     B  2010Q1        30        20
5     B  2010Q2        30        25
6     B  2010Q3        40        45
7     B  2010Q4        55        55
8     C  2010Q1        20        25
9     C  2010Q2        25        35
10    C  2010Q3        40        40
11    C  2010Q4        55        65