简体   繁体   中英

Create a new pandas dataframe from a python list of lists with a column with lists

I have a python list of lists, eg [["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.

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!

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]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM