0
votes

I have a data frame like this,

df
col1    col2 (the type is list) 
 1      [a]
 2      [a,b]
 3      [b]
 4      [a,b,c]

Here col1 values are unique. Now I want to create few more rows where the length of list is more than 1 and col1 values will be same in those cases. So the final data frame should look like,

df
col1    col2
 1       [a]
 2       [a]
 2       [b]
 3       [b]
 4       [a]
 4       [b]
 4       [c]

I could do this using for loop and iterate over the length of the list but it will take more time so looking for some pandas short cuts to do it more efficiently.

1

1 Answers

0
votes

Use DataFrame.explode first and then for one element lists lambda function:

df = df.explode('col2')
df['col2'] = df['col2'].apply(lambda x: [x])