0

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

if I have two nested list called entry, exit. How to add two nested list into dataframe. I tried df = (pd.DataFrame(entry,exit, columns=['Buy Date', 'Buy Entry','Buy Exit Date', 'Buy Exit']).explode('Buy Entry','Buy Exit', ignore_index=True)) But getting Error: ValueError: 4 columns passed, passed data had 2 columns How to solve this
@Divyank Don't know the structure of your entry and exit, you can ask a new question.

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.