2

I have a data frame that looks like below:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id':[1,2,3],'class':[7,5,3], 'grades':[[4,5,6],[8],[]]})

what I am trying to do here is that I want to duplicate each row for the number of element in the list in "grades" column.

It is kind of hard to explain, so it will be better to show the desired output.

output = pd.DataFrame({'id':[1,1,1,2,3],'class':[7,7,7,5,3], 'grades':[4,5,6,8, np.nan]})

I have look through some solutions, but could not figure out a way.

It will be great if someone can provide a guidance.

0

1 Answer 1

3

it is explode

df.explode('grades')

Out[11]:
   id  class grades
0   1      7      4
0   1      7      5
0   1      7      6
1   2      5      8
2   3      3    NaN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.