【问题标题】:Reshape Pandas dataframe that contains all years in one column and months separated across multiple columns重塑 Pandas 数据框,在一列中包含所有年份,并在多列中分隔月份
【发布时间】:2020-09-29 21:21:55
【问题描述】:

我有一个数据框,其中包含不同年份不同时间段内每种产品的销售额:

df = pd.DataFrame({'Product': {0: '1', 1: '1', 2: '2', 3: '2'},
                   'Year': {0: 2000, 1: 2001, 2: 2001, 3:2002},
                   'Jan-Feb': {0: 2, 1: 4, 2: 2, 3:4},
                    'Mar-Apr': {0: 1, 1: 2, 2: 1, 3:6}})

df 的产品有产品 1 和产品 2 对每个 year 的销售额,但一年内的时间段显示在不同的列中。在此示例中,我展示了两列,但还有四列表示一年内连续两个月的剩余时间段。

我想将df 重塑为如下所示:

df2 = pd.DataFrame({'Product': {0: '1', 1: '1', 2: '1', 3: '1', 4: '2', 5: '2', 6: '2', 7: '2'},
                   'Year': {0: 2000, 1: 2000, 2: 2001, 3:2001,4: 2001, 5: 2001, 6: 2002, 7:2002},
                   'Period': {0: 'Jan-Feb', 1: 'Mar-Apr', 2: 'Jan-Feb', 3:'Mar-Apr', 4: 'Jan-Feb', 5: 'Mar-Apr', 6: 'Jan-Feb', 7:'Mar-Apr'},
                   'Sales': {0: 2, 1: 1, 2: 4, 3: 2, 4: 2, 5: 1, 6: 4, 7: 6}})

在这种情况下,月份都在一个列中,而销售额则在不同的列中。我尝试了不同形式的重塑,但我显然遗漏了一些东西,因为我没有成功找到一种可以满足我想要的东西。

【问题讨论】:

    标签: python pandas dataframe reshape


    【解决方案1】:

    检查melt

    out = df.melt(['Product','Year'], var_name = 'Period', value_name = 'Sales')
      Product  Year   Period  Sales
    0       1  2000  Jan-Feb      2
    1       1  2001  Jan-Feb      4
    2       2  2001  Jan-Feb      2
    3       2  2002  Jan-Feb      4
    4       1  2000  Mar-Apr      1
    5       1  2001  Mar-Apr      2
    6       2  2001  Mar-Apr      1
    7       2  2002  Mar-Apr      6
    

    【讨论】:

      【解决方案2】:

      使用stack():

      df = df.set_index(['Product','Year']).stack(0).reset_index()
      df.columns = ['Product','Year','Period','Sales']
      

      输出

        Product  Year   Period  Sales
      0       1  2000  Jan-Feb      2
      1       1  2000  Mar-Apr      1
      2       1  2001  Jan-Feb      4
      3       1  2001  Mar-Apr      2
      4       2  2001  Jan-Feb      2
      5       2  2001  Mar-Apr      1
      6       2  2002  Jan-Feb      4
      7       2  2002  Mar-Apr      6
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        • 1970-01-01
        • 2023-01-01
        • 1970-01-01
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多