Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert nested list to a dataframe using Pandas Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pd.DataFrame(lisA)

What is the best way to convert the nested list (lisA) to a dataframe shown above?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading