如何在 Python 中使用来自数组输出的数据创建表

我打印出组合数组并保存到文本文件中,如下所示:


({

    ngram_a67e6f3205f0-n: 1,

    logreg_c120232d9faa-regParam: 0.01,

    cntVec_9c0e7831261d-vocabSize: 10000

},0.8580469779197205)

({

    ngram_a67e6f3205f0-n: 2,

    logreg_c120232d9faa-regParam: 0.01,

    cntVec_9c0e7831261d-vocabSize: 10000

},0.8880895806519427)

({

    ngram_a67e6f3205f0-n: 3,

    logreg_c120232d9faa-regParam: 0.01,

    cntVec_9c0e7831261d-vocabSize: 10000

},0.8656452460818544)

我希望提取数据来生成 python Dataframe,它就像:


1, 10000, 0.8580469779197205

2, 10000, 0.8880895806519427


扬帆大鱼
浏览 193回答 2
2回答

幕布斯7119047

我的建议是尽可能更改文件的输入格式。这将大大简化您的生活。如果这是不可能的,以下代码可以解决您的问题:import pandas as pdimport repattern_tuples = '(?<=\()[^\)]*'pattern_numbers = '[ ,](?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?'col_name = ['ngram', 'logreg', 'vocabSize', 'score']with open('test.txt','r') as f:&nbsp; &nbsp; matchs = re.findall(pattern_tuples, f.read())&nbsp; &nbsp; arr_data = [[float(val.replace(',','')) for val in re.findall(pattern_numbers, match)] for match in matchs]&nbsp; &nbsp; df = pd.DataFrame(arr_data, columns=col_name).astype({'ngram':'int', 'vocabSize': 'int'})并给出:&nbsp; &nbsp;ngram&nbsp; logreg&nbsp; vocabSize&nbsp; &nbsp; &nbsp;score0&nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; 0.01&nbsp; &nbsp; &nbsp; 10000&nbsp; 0.8580471&nbsp; &nbsp; &nbsp; 2&nbsp; &nbsp; 0.01&nbsp; &nbsp; &nbsp; 10000&nbsp; 0.8880902&nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; 0.01&nbsp; &nbsp; &nbsp; 10000&nbsp; 0.865645简要说明读取文件使用re.findall和正则表达式pattern_tuples查找文件中的所有元组对于每个元组,使用正则表达式pattern_numbers你会找到你感兴趣的 4 个数值。通过这种方式,您将获得包含您的数据的列表列表在 pandas 数据框中输入结果额外的以下是您如何将简历结果保存为json 格式,以便您更轻松地管理它们:创建一个cv_results数组来保存 CV 结果对于每个循环的 CV,您将获得一个t包含结果的元组,您必须将其转换为字典并挂在数组中cv_results在 CV 循环结束时,将结果保存为 json 格式.cv_results = []for _ in range_cv: # Loop CV&nbsp; &nbsp; # ... Calculate results of CV in t&nbsp; &nbsp; t = ({'ngram_a67e6f3205f0-n': 1,&nbsp; &nbsp; &nbsp; &nbsp;'logreg_c120232d9faa-regParam': 0.01,&nbsp; &nbsp; &nbsp; &nbsp;'cntVec_9c0e7831261d-vocabSize': 10000},&nbsp; &nbsp; &nbsp; 0.8580469779197205) # FAKE DATA for this example&nbsp; &nbsp; # append results like a dict&nbsp; &nbsp; cv_results.append({'res':t[0], 'score':t[1]})# Store results in json formatwith open('cv_results.json', 'w') as outfile:&nbsp; &nbsp; json.dump(cv_results, outfile, indent=4)现在您可以读取 json 文件,并且可以像普通 python 字典一样访问所有字段:with open('cv_results.json') as json_file:&nbsp; &nbsp; data = json.load(json_file)data[0]['score']# output: 0.8580469779197205

慕少森

为什么不这样做:import pandas as pdWith open(file.txt) as file:&nbsp; &nbsp; df = pd.DataFrame([i for i in eval(file.readline())])Eval 接受一个字符串并将其转换为非常漂亮的文字 python 表示形式。这会将每个括号转换为单个项目迭代器,然后将其存储到列表中。Pd 数据框类可以获取具有相同键的字典列表并创建数据框
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python