Pandas column of lists, create a row for each list element

前端 未结 10 777
有刺的猬
有刺的猬 2020-11-22 06:59

I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple values in a cell, I\'d like to expand the dataframe so that each item in t

10条回答
  •  心在旅途
    2020-11-22 07:51

    For those looking for a version of Roman Pekar's answer that avoids manual column naming:

    column_to_explode = 'samples'
    res = (df
           .set_index([x for x in df.columns if x != column_to_explode])[column_to_explode]
           .apply(pd.Series)
           .stack()
           .reset_index())
    res = res.rename(columns={
              res.columns[-2]:'exploded_{}_index'.format(column_to_explode),
              res.columns[-1]: '{}_exploded'.format(column_to_explode)})
    

提交回复
热议问题