【问题标题】:Python dataframe exploded list column into multiple rows [duplicate]Python数据框将列表列分解为多行[重复]
【发布时间】:2018-03-26 05:16:26
【问题描述】:

我有一个这样的数据框:

         desc     id     info  
       [a,b,c]     2     type
       [u,v,w]     18    tail

三列:desc、id、info 和 desc 是一个列表。我想要这个:

        des    id    info 
         a      2     type
         b      2     type
         c      2     type 
         u      18    tail
         v      18    tail
         w      18    tail

这意味着将列表列分解为多行,其他列没有变化。 我真的不知道该怎么做......

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这是一种方法

    df.set_index(['id', 'info']).desc.apply(pd.Series).stack()\
    .reset_index(name = 'desc').drop('level_2', axis = 1)
    
    
        id  info    desc
    0   2   type    a
    1   2   type    b
    2   2   type    c
    3   18  tail    u
    4   18  tail    v
    5   18  tail    w
    

    【讨论】:

    • 它有效。非常感谢。
    【解决方案2】:

    我记得这应该来自 piRSquared 或 cᴏʟᴅsᴘᴇᴇᴅ,但找不到链接...

    idx = np.arange(len(df)).repeat(df.desc.str.len(), 0)
    out = df.iloc[idx, ].assign(desc=np.concatenate(df.desc.values))
    out
    Out[100]: 
      desc  id  info
    0    a   2  type
    0    b   2  type
    0    c   2  type
    1    u  18  tail
    1    v  18  tail
    1    w  18  tail
    

    【讨论】:

      【解决方案3】:

      您可以将desc 列、repeat 其他两列展平,然后将它们连接起来:

      pd.concat([
          pd.Series([e for s in df.desc for e in s], name='desc'),
          df.drop('desc', 1).apply(lambda col: col.repeat(df.desc.str.len())).reset_index(drop=True)
      ], axis=1)
      
      #desc   id  info
      #0  a    2  type
      #1  b    2  type
      #2  c    2  type
      #3  u   18  tail
      #4  v   18  tail
      #5  w   18  tail
      

      【讨论】:

        【解决方案4】:

        你可以

        In [1631]: (df.loc[df.index.repeat(df.desc.str.len())]
                      .assign(desc=[v for x in df.desc.values for v in x]))
        Out[1631]:
          desc  id  info
        0    a   2  type
        0    b   2  type
        0    c   2  type
        1    u  18  tail
        1    v  18  tail
        1    w  18  tail
        

        【讨论】:

          猜你喜欢
          • 2018-10-31
          • 1970-01-01
          • 2019-12-28
          • 1970-01-01
          • 2018-07-26
          • 2020-05-17
          • 2013-01-27
          • 2016-10-13
          相关资源
          最近更新 更多