【问题标题】:Pandas DataFrame stack multiple column values into single columnPandas DataFrame 将多列值堆叠到单列中
【发布时间】:2016-03-26 08:51:18
【问题描述】:

假设如下DataFrame:

  key.0 key.1 key.2  topic
1   abc   def   ghi      8
2   xab   xcd   xef      9

如何将所有 key.* 列的值组合成单个列“key”,该列与 key.* 列对应的主题值相关联?这是我想要的结果:

   topic  key
1      8  abc
2      8  def
3      8  ghi
4      9  xab
5      9  xcd
6      9  xef

请注意,key.N 列的数量在某些外部 N 上是可变的。

【问题讨论】:

    标签: python pandas dataframe melt


    【解决方案1】:

    你可以融化你的数据框:

    >>> keys = [c for c in df if c.startswith('key.')]
    >>> pd.melt(df, id_vars='topic', value_vars=keys, value_name='key')
    
       topic variable  key
    0      8    key.0  abc
    1      9    key.0  xab
    2      8    key.1  def
    3      9    key.1  xcd
    4      8    key.2  ghi
    5      9    key.2  xef
    

    它还为您提供了密钥的来源。


    v0.20meltpd.DataFrame 类的第一类函数:

    >>> df.melt('topic', value_name='key').drop('variable', 1)
    
       topic  key
    0      8  abc
    1      9  xab
    2      8  def
    3      9  xcd
    4      8  ghi
    5      9  xef
    

    【讨论】:

      【解决方案2】:

      好的,因为当前答案之一被标记为与此问题重复,我将在这里回答。

      通过使用wide_to_long

      pd.wide_to_long(df, ['key'], 'topic', 'age').reset_index().drop('age',1)
      Out[123]: 
         topic  key
      0      8  abc
      1      9  xab
      2      8  def
      3      9  xcd
      4      8  ghi
      5      9  xef
      

      【讨论】:

        【解决方案3】:

        在尝试了各种方法后,我发现以下内容或多或少是直观的,前提是了解stack的魔力:

        # keep topic as index, stack other columns 'against' it
        stacked = df.set_index('topic').stack()
        # set the name of the new series created
        df = stacked.reset_index(name='key')
        # drop the 'source' level (key.*)
        df.drop('level_1', axis=1, inplace=True)
        

        根据需要生成的数据框:

           topic  key
        0      8  abc
        1      8  def
        2      8  ghi
        3      9  xab
        4      9  xcd
        5      9  xef
        

        您可能需要打印中间结果以全面了解该过程。如果您不介意列数超出所需,关键步骤是set_index('topic')stack()reset_index(name='key')

        【讨论】:

        • 我似乎找不到关于 name 参数的任何文档 reset_index,你能解释一下它是如何工作的吗?
        猜你喜欢
        • 2018-06-19
        • 1970-01-01
        • 2016-12-08
        • 2016-11-02
        • 1970-01-01
        • 2015-02-15
        • 2018-11-02
        相关资源
        最近更新 更多