【问题标题】:Reshape dataframe in Pandas from long to wide format with new column names使用新列名将 Pandas 中的数据框从长格式改写为宽格式
【发布时间】:2020-11-01 18:57:44
【问题描述】:

我有一个需要重新整形的数据框(示例如下)。我希望每行只有一个唯一用户,但是,现在,每个用户在数据框中有两行,基于“testday”列(基线和 D7)具有不同的值。我想要的是根据 testday 组的列名重命名值列('01. Tristeza Aparente)。因此,新的值列将类似于“Basel_Tristeza Aparente”和“D7_01”。 Tristeza Aparente'

我在Pivotunstack 上准备的教程不太奏效,因为我不想汇总数据。将用户折叠成一行时,我只需要不同的列。谢谢,如果我能让这个问题更清楚,请告诉我

  {'01. Tristeza Aparente': {0: 4.0,
  1: 4.0,
  2: 4.0,
  3: 2.0,
  4: 1.0,
  5: 0.0,
  6: 3.0},
 '02. Tristeza Expressa': {0: 6.0,
  1: 6.0,
  2: 4.0,
  3: 0.0,
  4: 4.0,
  5: 3.0,
  6: 6.0},
 'group': {0: 'placebo',
  1: 'placebo',
  2: 'placebo',
  3: 'placebo',
  4: 'placebo',
  5: 'placebo',
  6: 'placebo'},
 'subject': {0: 1.0, 1: nan, 2: 2.0, 3: nan, 4: 3.0, 5: nan, 6: 4.0},
 'subjectedit': {0: 1.0, 1: 1.0, 2: 2.0, 3: 2.0, 4: 3.0, 5: 3.0, 6: 4.0},
 'testday': {0: 'Basal',
  1: 'D7',
  2: 'Basal',
  3: 'D7',
  4: 'Basal',
  5: 'D7',
  6: 'Basal'}}

【问题讨论】:

    标签: python pandas reshape


    【解决方案1】:

    您可以pivot 数据框并使用带有格式的字符串重命名列f,但请确保您使用的是最新版本的熊猫,因为枢轴与早期版本相比有问题。

    df = df.pivot(index=['group', 'subjectedit'], columns='testday')
    df.columns = [f'{col[1]}_{col[0]}' for col in df.columns]
    df
    Out[1]: 
                         Basal_01. Tristeza Aparente  D7_01. Tristeza Aparente  \
    group   subjectedit                                                          
    placebo 1.0                                  4.0                       4.0   
            2.0                                  4.0                       2.0   
            3.0                                  1.0                       0.0   
            4.0                                  3.0                       NaN   
    
                         Basal_02. Tristeza Expressa  D7_02. Tristeza Expressa  \
    group   subjectedit                                                          
    placebo 1.0                                  6.0                       6.0   
            2.0                                  4.0                       0.0   
            3.0                                  4.0                       3.0   
            4.0                                  6.0                       NaN   
    
                         Basal_subject  D7_subject  
    group   subjectedit                             
    placebo 1.0                    1.0         NaN  
            2.0                    2.0         NaN  
            3.0                    3.0         NaN  
            4.0                    4.0         NaN  
    

    【讨论】:

      【解决方案2】:

      df['new_column'] = df['testday'] + '_' + '01. Tristeza Aparente'会解决您的问题吗?您也可以将其分配给现有列。

      【讨论】:

        猜你喜欢
        • 2021-05-12
        • 2019-05-31
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多