Search code examples
pythondataframesklearn-pandas

how to convert a list of list to dataframe keeping the grouping value of another column?


I have a df with a column in which each row is a list and another column with the list name. I want to convert the elements of each list in a row into separate rows while keeping the list name in another column. example below. original data

I want to convert this data set into this:

modified data

I have done this using the below code:

data = []
group = []
for i in df.index:
    for j in df.Data.loc[i]:
        data.append(j)
    for group_data in range(len(df.Data.loc[i])): 
        group.append(df.Group.loc[i])

Is there a more elegant way or inbuilt function for this in python?


Solution

  • This should work

    df = df.explode('Data').reset_index(drop=True)