将整个列表放在一个dataframe列中

2024-04-26 00:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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]

Tags: 数据namefrom命令dataframedfindex字典
3条回答

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

当您使用from_dict类方法时,您将获得方向选项,该选项允许您指定字典的键是否表示行或列标签,但字典的“类似列表”值仍将被解释为新列或新行。你知道吗

使用这两种方法还要求值的长度是一致的。你知道吗


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

相反,您对一维pd.Series感兴趣,它将使用一个字典并将每个键用作行标签,将每个值用作行值。你知道吗

pd.Series(dct)

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

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

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

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

使用dict创建序列并转换为数据帧:

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

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

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

注意:请不要使用dict作为变量名。这是个坏习惯。你知道吗

pd.DataFrame({'col_name': pd.Series(dict)})  

结果:

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

相关问题 更多 >