1

I have a python list of lists, e.g. [["chunky","bacon","foxes"],["dr_cham"],["organ","instructor"],...] and would like to create a pandas dataframe with one column containing the lists:

 0 ["chunky","bacon","foxes"] 
 1 ["dr_cham"] 
 2 ["organ","instructor"] .
 . .

The std constructor (l is the list here)

pd.DataFrame(l)

returns a dataframe with 3 columns in that case.

How would this work? I'm sure it's very simple, but I'm searching for a solution since a while and can't figure it out for some obscure reason.

Thanks, B.

1
  • In connection with the name of your list, you might wanna read this. Commented Mar 28, 2018 at 18:48

2 Answers 2

2

The following code should achieve what you want:

import pandas as pd

l = [["hello", "goodbye"], ["cat", "dog"]]

# Replace "lists" with whatever you want to name the column
df = pd.DataFrame({"lists": l})

After printing df, we get

              lists
0  [hello, goodbye]
1        [cat, dog]

Hope this helps -- let me know if I can clarify anything!

Sign up to request clarification or add additional context in comments.

6 Comments

I agree, using a dictionary is the best approach.
thanks a million, that was exactly what i was looking for!
Happy to help @user3379621!
How do I create a Pandas df where all the elements of the lists are in separate columns as well? @PeterDolan For example from the OP's original question itself, I'd want hello in column 1 and goodbye in column 2. For the second row, cat in column 1, and dog in column 2
I did, @Peter Dolan and I have got a satisfactory answer. Cheers!
|
1

This pattern is rarely if ever a good idea and defeats the purpose of Pandas, but if you have some unusual use case that requires it, you can achieve it by further nesting your inner lists an additional level in your main list, then creating a DataFrame from that:

l = [[x] for x in l]
df = pd.DataFrame(l)

                        0
0  [chunky, bacon, foxes]
1               [dr_cham]
2     [organ, instructor]

1 Comment

I know, but it's a very specific problem.

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.