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

Time:05-31

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?

CodePudding user response:

This should work

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

CodePudding user response:

simplest way is make the list and then replace it :

df = df.reset_index()  # make sure indexes pair with number of rows
newlist = []
newlist.append(['Group','Data'])   # for headers
for index, row in df.iterrows():
    values = str(row['Date']).split(',')
    for value in values :
        newlist.append([row['Group'] , value)
df = pd.Dataframe(newlist)
  • Related