【问题标题】:Pandas: if column names are the same, I want to stack them on top of each other熊猫:如果列名相同,我想将它们堆叠在一起
【发布时间】:2022-12-11 19:36:17
【问题描述】:

我有一个表如下:

id a b a b c color
123 1 6 7 3 4 blue
456 2 8 9 7 5 yellow

如您所见,某些列具有相同的内容。我想要做的是将具有相同名称的列堆叠在一起(使表格长于宽)。我查看了 stack、melt 和 pivot 的文档,但找不到与此处类似的问题。谁能帮助我如何实现这一目标?

仅供参考,这是我需要表格的方式:

id a b c color
123 1 6 4 blue
123 7 3 4 blue
456 2 8 5 yellow
456 9 7 5 yellow

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用groupby.cumcountstackgroupby.ffill 删除重复值:

    (df.set_axis(pd.MultiIndex.from_arrays([df.columns,
                                            df.groupby(level=0, axis=1).cumcount()
                                           ]), axis=1)
       .stack().groupby(level=0).ffill()
       .reset_index(drop=True).convert_dtypes() # optional
       [list(dict.fromkeys(df.columns))] # also optional, keep original order
    )
    

    输出:

        id  a  b  c   color
    0  123  1  6  4    blue
    1  123  7  3  4    blue
    2  456  2  8  5  yellow
    3  456  9  7  5  yellow
    

    【讨论】:

    • 这很聪明!非常感谢!我一直在寻找答案有一段时间了!
    【解决方案2】:
    # melt to turn wide to long format
    df2=df.melt(id_vars=['id']) 
    
    (df2.assign(seq=df2.groupby(['variable']).cumcount()) # assign a seq to create multiple rows for an id
     .pivot(index=['id','seq'], columns='variable', values='value' ) # pivot
     .reset_index()
     .drop(columns='seq')
     .rename_axis(columns=None)
    ).ffill()  # fill nan with previous value
    
    
    id  a   b   c   color
    0   123     1   6   4   blue
    1   123     7   3   4   blue
    2   456     2   8   5   yellow
    3   456     9   7   5   yellow
    

    【讨论】:

      【解决方案3】:

      一种选择是来自pyjanitorpivot_longer;我添加了一个临时列c1,所以所有列的数字都有平衡:

      (df
      .assign(c1=df.c)
      .pivot_longer(
          index = ['id', 'color'], 
          names_to = '.value', 
          names_pattern = '(.)')
      )
          id   color  a  b  c
      0  123    blue  1  6  4
      1  456  yellow  2  8  5
      2  123    blue  7  3  4
      3  456  yellow  9  7  5
      

      【讨论】:

        猜你喜欢
        • 2021-03-06
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多