1

How to explode the list into rows?

I have the following data frame:

df = pd.DataFrame([
        (1,
            [1,2,3],
            ['a','b','c']
        ),
        (2,
            [4,5,6],
            ['d','e','f']
        ),
        (3,
            [7,8],
            ['g','h']
        )
])

Shown in output as follows

   0          1          2
0  1  [1, 2, 3]  [a, b, c]
1  2  [4, 5, 6]  [d, e, f]
2  3     [7, 8]     [g, h]

I want to have the following output:

    0   1   2
0   1   1   a
1   1   2   b
2   1   3   c
3   2   4   d
4   2   5   e
5   2   6   f
6   3   7   g
7   3   8   h

1 Answer 1

2

You can use str.len for get length of lists which are repeated by numpy.repeat with flattening lists:

from  itertools import chain
import numpy as np

df2 = pd.DataFrame({
        0: np.repeat(df.iloc[:,0].values, df.iloc[:,1].str.len()),
        1: list(chain.from_iterable(df.iloc[:,1])),
        2: list(chain.from_iterable(df.iloc[:,2]))})

print (df2)        
   0  1  2
0  1  1  a
1  1  2  b
2  1  3  c
3  2  4  d
4  2  5  e
5  2  6  f
6  3  7  g
7  3  8  h
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.