Skip to main content
 首页 » 编程设计

python之将整个列表放在一个数据框列中

2025年05月04日14shanyou

我正在尝试从字典创建数据框:

dict = {'foo': [1, 2, 3, 4], 
        'bar': [5, 6, 7, 8]} 

然后我使用以下命令创建数据框:

df = pd.DataFrame.from_dict(dict, orient='index') 

但是输出是这样的:

df: 
           0  1  2  3 
     foo   1  2  3  4 
     bar   4  5  6  7 

但我希望输出如下所示,只有一列:

df: 
           'column_name' 
     foo    [1, 2, 3, 4] 
     bar    [4, 5, 6, 7] 

请您参考如下方法:

您正在传递一个包含“类似列表”值的字典。当传递给 DataFrame 构造函数 时,pandas 将字典的键解释为系列标签,并将每个列表中的值解释为每个系列的新行值。

当您使用 from_dict 类方法时,您可以选择方向,它允许您指定字典的键是否代表行或列标签,但是“列表- like”字典的值仍将被解释为新列或新行。

使用这两种方法还要求值的长度是统一的。


pd.DataFrame.from_dict(dct, orient='index') 

     0  1  2  3 
foo  1  2  3  4 
bar  5  6  7  8 

pd.DataFrame.from_dict(dct, orient='columns') 

   foo  bar 
0    1    5 
1    2    6 
2    3    7 
3    4    8 

相反,您对 1-Dimensional pd.Series 感兴趣,它将使用字典并将每个键用作行标签,将每个值用作行值。

pd.Series(dct) 

foo    [1, 2, 3, 4] 
bar    [5, 6, 7, 8] 
dtype: object 

根据我上面的评论,如果您对 DataFrame 感兴趣,可以使用 to_frame,它将维护存储在 Series 中的值。

pd.Series(dct).to_frame('column_name') 

      column_name 
foo  [1, 2, 3, 4] 
bar  [5, 6, 7, 8]