Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (18.4k points)
edited by

I have the list of lists (that contains tuples):

mylist = [[0, ('a',3), ('b',4), ('c',5)], [1, ('a',2), ('d',7), ('e',6)], [2, ('b',1), ('a',2), ('d',3)]]

I would like to convert it to a long data frame. My expected output:

v1  v2  v3 

0   a   3

0   b   4

0   c   5

1   a   2

1   d   7

1   e   6

2   b   1

2   a   2

2   d   3

1 Answer

0 votes
by (36.8k points)
edited by

You can try this using the list comprehension and tuple unpacking.

#          (0, 'a', 3)

#               |

pd.DataFrame([(i,*t) for i,*v in mylist for t in v])

# In 1st iteration       |  |               |

#                        0  |            ('a', 3)

#               [('a', 3), ('b', 4), ('c', 5)]

   0  1  2

0  0  a  3

1  0  b  4

2  0  c  5

3  1  a  2

4  1  d  7

5  1  e  6

6  2  b  1

7  2  a  2

8  2  d  3

 Do check out Data Science with Python course which helps you understand from scratch.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...