How to explode a list inside a Dataframe cell into separate rows

后端 未结 11 2348
天命终不由人
天命终不由人 2020-11-22 10:20

I\'m looking to turn a pandas cell containing a list into rows for each of those values.

So, take this:

If I\'d like to unpack and stack the value

11条回答
  •  半阙折子戏
    2020-11-22 11:14

    Nicer alternative solution with apply(pd.Series):

    df = pd.DataFrame({'listcol':[[1,2,3],[4,5,6]]})
    
    # expand df.listcol into its own dataframe
    tags = df['listcol'].apply(pd.Series)
    
    # rename each variable is listcol
    tags = tags.rename(columns = lambda x : 'listcol_' + str(x))
    
    # join the tags dataframe back to the original dataframe
    df = pd.concat([df[:], tags[:]], axis=1)
    

提交回复
热议问题