简体   繁体   English

从列表的python列表和带有列表的列创建新的pandas数据框

[英]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: 我有一个清单的python清单,例如[["chunky","bacon","foxes"],["dr_cham"],["organ","instructor"],...]并想创建一个熊猫数据框,其中一列包含列表:

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

The std constructor (l is the list here) std构造函数(l是此处的列表)

pd.DataFrame(l)

returns a dataframe with 3 columns in that case. 在这种情况下,返回包含3列的数据框。

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. 谢谢,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 打印df ,我们得到

              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: 这种模式很少是一个好主意,并且无法达到Pandas的目的,但是如果您有一些不寻常的用例需要它,则可以通过将内部列表进一步嵌套在主列表中的另一个级别,然后创建一个DataFrame来实现。从中:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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