I have a 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 dataframe. 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
Thanks for your time and help!
You can try this using 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
Here's one way of doing it by padding your tuples with the first item:
s = [(x[0],)+ y for x in mylist for y in x[1:]]
print (pd.DataFrame(s, columns=["v1","v2","v3"]))
v1 v2 v3
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
newmylist = []
for i in mylist:
for j in i[1:]:
newmylist.append((i[0],) + j)
pd.DataFrame(newmylist, columns=["v1","v2","v3"])
Output:
v1 v2 v3
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.