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

后端 未结 11 2349
天命终不由人
天命终不由人 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:18

    Use apply(pd.Series) and stack, then reset_index and to_frame

    In [1803]: (df.nearest_neighbors.apply(pd.Series)
                  .stack()
                  .reset_index(level=2, drop=True)
                  .to_frame('nearest_neighbors'))
    Out[1803]:
                        nearest_neighbors
    name       opponent
    A.J. Price 76ers          Zach LaVine
               76ers           Jeremy Lin
               76ers        Nate Robinson
               76ers                Isaia
               blazers        Zach LaVine
               blazers         Jeremy Lin
               blazers      Nate Robinson
               blazers              Isaia
               bobcats        Zach LaVine
               bobcats         Jeremy Lin
               bobcats      Nate Robinson
               bobcats              Isaia
    

    Details

    In [1804]: df
    Out[1804]:
                                                       nearest_neighbors
    name       opponent
    A.J. Price 76ers     [Zach LaVine, Jeremy Lin, Nate Robinson, Isaia]
               blazers   [Zach LaVine, Jeremy Lin, Nate Robinson, Isaia]
               bobcats   [Zach LaVine, Jeremy Lin, Nate Robinson, Isaia]
    

提交回复
热议问题