【问题标题】:Pandas DF Creating from Dictionary Error: ValueError: If using all scalar values, you must pass an indexPandas DF Creating from Dictionary Error: ValueError: If using all scalar values, you must pass an index
【发布时间】:2020-11-19 08:03:18
【问题描述】:

您好,我正在用这段代码创建一个 Pandas DF:

for odfslogp_obj in odfslogs_plist:
        with zipfile.ZipFile(odfslogp_obj, mode='r') as z:
            for name in z.namelist():
                with z.open(name) as etest_zip:
                    tdict = {}
                    etestlines = [line.decode() for line in etest_zip] #change lines from log files from binary to text
                    regval_range_tup_list = list(zip([i for i,x in enumerate(etestlines) if 'Head' in x ],  [i for i,x in enumerate(etestlines) if 'BINS' in x ])) #get binval sections
                    head_siteparam_tup_list = list(zip([x.split("=")[1].replace("(",'').replace(")",'').rstrip() for x in etestlines if 'Head' in x], [x.split(":")[2].rstrip() for x in etestlines if 'SITE:PARAM_SITE:' in x])) #extract head and site:param values from bin val sections

                    print(head_siteparam_tup_list)
                    linesineed = [etestlines[range[0]:range[1]-1] for range in regval_range_tup_list]
                    reglinecount = []
                    regvals = []
                    for head_site, loclist in zip(head_siteparam_tup_list, linesineed):
                        regvals_ext = [x for x in loclist if pattern.search(x)]
                        regvaltups_list = [tuple(x.split(":")[0:2]) for x in regvals_ext]
                        regvaldict = dict(regvaltups_list)
                        df = pd.DataFrame(data=regvaldict)
                        print(df)

正在使用的字典的输出示例在打印时如下所示:

{'1000': '1669.15', '10012': '-0.674219', '10013': '-0.260156', '1003': '9.5792', '1007': '11.9812', '1011': '27.888', '1012': '14.8333', '1014': '19.1812', '1015': '19.0396', '1024': '1352.66', '1025': '3247.63', '1026': '33.7434', '1027': '38.7566', '1030': '19.7548', '1031': '30.2201'}

如您所见,它们都是字符串,那么为什么会出现此错误?我该如何解决?

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    检查.from_dict()中的参数orient

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

    另一种选择:

    pd.DataFrame(dic.keys(), index = dic.values())
    

    输出:

            0
    1000    1669.15
    10012   -0.674219
    10013   -0.260156
    ...
    

    或者,如果您不想将键作为索引:

    pd.DataFrame(dic.items())
    

    输出:

        0       1
    0   1000    1669.15
    1   10012   -0.674219
    2   10013   -0.260156
    

    【讨论】:

    • 嗯,但我没有使用 .from_dict() 函数。我尝试使用尽可能少的函数来最大限度地减少任何潜在的开销时间,因为我将处理大量文件
    • 检查第二个选项,以防它更适合您的情况。
    • 不幸的是,这些都不起作用。我通过使用字典列表找到了解决方案。但是谢谢你的努力!我已经抄下了你的方法,以防不同的用例要求我使用它们
    【解决方案2】:

    我通过使用字典列表而不是传递字典找到了我要查找的内容。

    这不仅帮助我添加了不同的字典,而且简化了代码,让我可以轻松地从字典的聚合列表中创建一个数据框,使其完全符合我的期望:

         for head_site, loclist in zip(head_siteparam_tup_list, linesineed):
                      
                        regvals_ext = [x for x in loclist if pattern.search(x)]
                        #print(regvals_ext)
                        regvaltups_list = [tuple(x.split(":")[0:2]) for x in regvals_ext]
                        
                        regvaldict = dict(regvaltups_list)
                        regvaltupaggr_list.append(regvaldict)
                        
                    regvalfile_df = pd.DataFrame(regvaltupaggr_list)
                    # print(regvalfile_df)
                    regvalfile_df.to_csv(r"C:\Users\sys_nsgprobeingestio\Documents\dozie\odfs\etest\filebinval.csv", index=False)
    

    输出:

    1000      10012      10013     1003     1007    1011     1012     1014     1015     1024     1025     1026     1027  ...   9717   9718     9722     9723     9724     9725     9726     9727     9728     9729    9730       9912       9913
    0   1665.67  -0.678906  -0.267969  9.66017  12.0638  27.728  15.2347  19.9796   19.634  1352.33  3618.55   32.843  38.1179  ...  81.58  89.88  106.239  117.136  132.556  132.944   141.92   132.76  161.551  68.6192  67.325   -0.68125  -0.27031
    

    【讨论】:

      猜你喜欢
      • 2018-04-20
      • 2021-04-01
      • 2020-12-20
      • 2021-03-19
      • 2019-07-06
      • 2020-08-28
      • 1970-01-01
      • 2022-09-09
      • 2022-12-02
      相关资源
      最近更新 更多