【问题标题】:Dictionary to Dataframe Error: "If using all scalar values, you must pass an index"字典到数据框错误:“如果使用所有标量值,则必须传递索引”
【发布时间】:2019-12-29 02:37:52
【问题描述】:

目前,我正在使用 for 循环从文件夹中读取 csv 文件。 读取 csv 文件后,我将数据存储到字典的一行中。 当我使用“print(list_of_dfs.dtypes)”打印数据类型时,我收到:

dtype: 对象 日期时间:对象 值:float64 编号:int64 ID 名称:对象。

请注意,这是一个嵌套字典,在每个数据字段中存储了数千个值。我有上面列出的 26 行结构。我正在尝试将字典行附加到数据框中,其中只有 1 行包含数据字段:

索引 DATETIME VALUE ID ID 名称。

注意:我正在学习python。 我尝试使用数组来存储数据,然后将数组转换为数据帧,但我无法追加数据帧的行。

我尝试使用字典方法“df = pd.Dataframe(list_of_dfs)” 这会引发错误。

list_of_dfs = {} 

for I in range(0,len(regionLoadArray)
list_of_dfs[I] = pd.read_csv(regionLoadArray[I]) 

#regionLoadArray contains my- file names from list directory.

dataframe = pd.DataFrame(list_of_dfs)
#this method was suggested at thispoint.com for nested dictionaries.
#This is where my error occurs^

ValueError: 如果使用所有标量值,则必须传递索引

感谢您对这个问题的任何帮助,因为我是 python 新手。 我目前的目标是简单地生成一个带有我的标头的数据框,然后我可以将其发送到 csv。

【问题讨论】:

    标签: python excel pandas dataframe dictionary


    【解决方案1】:

    出现此错误是因为 pandas 需要索引。起初,这似乎有点令人困惑,因为您会想到列表索引。这本质上要求的是每个字典对应于每个字典的列号。你可以这样设置:

    import pandas as pd
    list = ['a', 'b', 'c', 'd']
    df = pd.DataFrame(list, index = [0, 1, 2, 3])
    

    然后数据框产生:

       0  
    0 'a'
    1 'b'
    2 'c'
    3 'd'
    

    具体来说,使用 numpy(未测试)可能看起来像这样:

    list_of_dfs = {} 
    
    for I in range(0,len(regionLoadArray)):
        list_of_dfs[I] = pd.read_csv(regionLoadArray[I]) 
    
    ind = np.arange[len(list_of_dfs)]
    
    dataframe = pd.DataFrame(list_of_dfs, index = ind)
    

    【讨论】:

    • 我尝试通过引入索引数组并在我的 for 循环中分配值来添加索引:“index[I] = I”,最后使用索引生成数据帧。但是我收到错误消息:“传递值的形状是 {0} ,索引暗示 {1}.format(passed,implied)
    • @Lonsdale_Energy,它需要整个列表。查看我的编辑。
    • 我假设 np 是 numpy。错误“模块'numpy'没有属性'arrange'”
    • 啊,这是一个错字。它应该是“范围”。是的,np 是 numpy。我已经改变了答案。
    • 知道了,我应该知道的。那行得通,但现在我有错误:“built+in_function_or_method”对象不可下标。
    【解决方案2】:

    不幸的是,Pandas 在创建 DataFrame 时总是需要索引。 您可以自己设置,也可以使用具有以下结构的对象,以便 pandas 可以自行确定索引:

        data= {'a':[1],'b':[2]}
    

    由于在您的案例中编辑数据并不容易,

    一个 hacky 解决方案是将数据包装到一个列表中

        dataframe = pd.DataFrame([list_of_dfs])
    

    【讨论】:

      【解决方案3】:

      根据您的需要,一个简单的解决方法可能是:

      dct = {'col1': 'abc', 'col2': 123}
      dct = {k:[v] for k,v in dct.items()}  # WORKAROUND
      df = pd.DataFrame(dct)
      

      导致

      print(df)
      
        col1  col2
      0  abc   123
      

      【讨论】:

        猜你喜欢
        • 2017-02-19
        • 1970-01-01
        • 2021-07-14
        • 1970-01-01
        • 2021-08-01
        • 2020-03-19
        • 2016-11-17
        相关资源
        最近更新 更多