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

时间:2019-10-04 00:45:43

标签: python dataframe

我打印出组成的数组并保存到文本文件中,就像:

({
    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

2 个答案:

答案 0 :(得分:3)

我的建议是,如果可能的话,请更改文件的输入格式。这将大大简化您的生活。
如果不可能,请使用以下代码解决您的问题:

import pandas as pd
import re

pattern_tuples = '(?<=\()[^\)]*'
pattern_numbers = '[ ,](?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?'
col_name = ['ngram', 'logreg', 'vocabSize', 'score']

with open('test.txt','r') as f:
    matchs = re.findall(pattern_tuples, f.read())
    arr_data = [[float(val.replace(',','')) for val in re.findall(pattern_numbers, match)] for match in matchs]
    df = pd.DataFrame(arr_data, columns=col_name).astype({'ngram':'int', 'vocabSize': 'int'})

并给出:

   ngram  logreg  vocabSize     score
0      1    0.01      10000  0.858047
1      2    0.01      10000  0.888090
2      3    0.01      10000  0.865645

简要说明

  1. 读取文件
  2. 使用re.findall和正则表达式pattern_tuples查找文件中的所有元组

  3. 对于每个元组,使用正则表达式pattern_numbers,您将找到您感兴趣的4个数值。这样,您将获得包含数据的列表列表

  4. 在熊猫数据框中输入结果


额外

以下是将您的简历结果保存为 json格式的方法,因此您可以更轻松地管理它们:

  1. 创建一个cv_results数组以保留简历结果

  2. 对于CV的每个循环,您将获得一个带有结果的元组t,您必须将其转换为字典并挂在数组cv_results

    li>
  3. 在CV循环结束时,将结果保存为json格式

cv_results = []

for _ in range_cv: # Loop CV
    # ... Calculate results of CV in t
    t = ({'ngram_a67e6f3205f0-n': 1,
       'logreg_c120232d9faa-regParam': 0.01,
       'cntVec_9c0e7831261d-vocabSize': 10000},
      0.8580469779197205) # FAKE DATA for this example

    # append results like a dict
    cv_results.append({'res':t[0], 'score':t[1]})

# Store results in json format
with open('cv_results.json', 'w') as outfile:
    json.dump(cv_results, outfile, indent=4)

现在您可以读取json文件,并且可以像普通的python字典一样访问所有字段:

with open('cv_results.json') as json_file:
    data = json.load(json_file)

data[0]['score']
# output: 0.8580469779197205

答案 1 :(得分:0)

为什么不这么做:

const arr = [{from: "2019,09,14", to: "2019,09,14"}];
 
//Helper function to split on comma, convert items to numbers
const toIntegerArray = str => str.split(",").map(Number);

const result = arr.map(({from,to}) => ({
  from: toIntegerArray(from),
  to: toIntegerArray(to)
}));

console.log(result);

Eval接受一个字符串,并将其转换为非常漂亮的文字python表示形式。这样会将每个括号转换为单个项目迭代器,然后将其存储到列表中。 PD数据框类可以使用具有相同键的字典列表来创建数据框