I have the below nested list:
lisA = [['Monday', ['Cherry', 'Mango']],
['Tuesday', ['Blueberry', 'Apple', 'Grape']],
['Wednesday', ['Apple', 'Orange']],
['Thursday', ['Watermelon', 'Kiwi', 'Apple']],
['Friday', ['Orange', 'Cherry']]]
I need to convert this nested list to a dataframe which looks like the below:
| Day | Item |
| -------- | -------------- |
| Monday | Cherry |
| Monday | Mango |
|Tuesday | Blueberry |
|Tuesday | Apple |
|Tuesday | Grape |
|Wednesday | Apple |
|Wednesday | Orange |
|Thursday | Watermelon |
|Thursday | Kiwi |
|Thursday | Apple |
|Friday | Orange |
|Friday | Cherry |
If I use the below code to convert the nested list to a dataframe, I get Monday in one column and the entire Monday list in another column
pd.DataFrame(lisA)
What is the best way to convert the nested list (lisA) to a dataframe shown above?
CodePudding user response:
You can try
df = (pd.DataFrame(lisA, columns=['Day', 'Item'])
.explode('Item', ignore_index=True))
print(df)
Day Item
0 Monday Cherry
1 Monday Mango
2 Tuesday Blueberry
3 Tuesday Apple
4 Tuesday Grape
5 Wednesday Apple
6 Wednesday Orange
7 Thursday Watermelon
8 Thursday Kiwi
9 Thursday Apple
10 Friday Orange
11 Friday Cherry