'Pandas zip multiple internal corresponding lists to long records [duplicate]

I don't think this is a typical wide to long question because the items I'm looking to turn to long are actually nested in list fields.

I have a uid field which is a list of integers, and another array which is a list of booleans that corresponds to the uid fields. I'd like to turn this array records into long records instead.

My data frame that looks like this:

    name          uid         is_left  colC colD colE ...
record01        [885]          [True]    ..   ..   .. ...
record02        [981]         [False]    ..   ..   .. ...
record03   [713, 981]   [False, True]    ..   ..   .. ...
record04        [713]          [True]    ..   ..   .. ...
record05        [126]          [True]    ..   ..   .. ...

I'd like to unwind it to:

    name          uid         is_left  colC colD colE ...
record01          885            True    ..   ..   .. ...
record02          981           False    ..   ..   .. ...
record03          713           False    ..   ..   .. ...
record03          981            True    ..   ..   .. ...
record04          713            True    ..   ..   .. ...
record05          126            True    ..   ..   .. ...

You can see record03 now has 2 entries, one for (713, False) and one for (981, True).



Solution 1:[1]

Better Answer:

In pandas 1.3 you can use multi-column explode:

df.explode(['uid','is_left'])

For older versions, explode each column individually:

df.apply(pd.Series.explode)

Old Answer:

You can use the explode method:

df.explode("uid").explode("is_left")

explode take the name of the column to convert from list elements to new rows.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1