【问题标题】:Change multiple columns into rows having three separate columns in python在python中将多列更改为具有三个单独列的行
【发布时间】:2021-07-15 08:53:25
【问题描述】:

示例源表

City Delivery in 2010Q1 Delivery in 2010Q2 Delivery in 2010Q3 Delivery in 2010Q4 Services in 2010Q1 Services in 2010Q2 Services in 2010Q3 Services in 2010Q4
A 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

结果表

City Period Delivery Services
A 2010Q1 10 20
A 2010Q2 15 25
A 2010Q3 20 30
A 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 功能,但无法获得所需的输出。

【问题讨论】:

    标签: python pandas dataframe numpy backend


    【解决方案1】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多