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

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

    I think this a really good question, in Hive you would use EXPLODE, I think there is a case to be made that Pandas should include this functionality by default. I would probably explode the list column with a nested generator comprehension like this:

    pd.DataFrame({
        "name": i[0],
        "opponent": i[1],
        "nearest_neighbor": neighbour
        }
        for i, row in df.iterrows() for neighbour in row.nearest_neighbors
        ).set_index(["name", "opponent"])
    

提交回复
热议问题