使用Python

时间:2018-09-01 08:13:45

标签: python numpy genfromtxt

我正在尝试使用python从.txt文件加载多列数据。

我的文件包含多组数据,每组都有一个标题。

我想选择一个集合,然后从中选择2列。 我正在使用genfromtxt来读取.txt文件,但是它以列的形式读取集合的标题,因此它给了我这种错误:

第2行(获得4列而不是1列)

这是我的txt文件的示例,其中TC_14TeV_NLO和TC_13TeV_LO是标题,而我想采用每组的前两列:

TC_14TeV_NLO 
1000 1.51100e+01 6.2e-03 4.1e-02%
2000 7.36556e-01 4.4e-04 5.9e-02%
3000 7.85092e-02 5.1e-05 6.5e-02%
4000 1.17810e-02 7.4e-06 6.3e-02%
5000 2.39873e-03 1.3e-06 5.2e-02%
6000 7.18132e-04 2.7e-07 3.7e-02%
7000 3.10281e-04 8.1e-08 2.6e-02%
8000 1.67493e-04 3.3e-08 1.9e-02%
9000 1.01369e-04 2.2e-08 2.2e-02%
10000 6.54776e-05 1.6e-08 2.4e-02%

TC_13TeV_LO
1000 1.04906e+01 1.7e-03 1.7e-02%
2000 4.53170e-01 8.1e-05 1.8e-02%
3000 4.25722e-02 7.9e-06 1.9e-02%
4000 5.80036e-03 1.1e-06 1.9e-02%
5000 1.17278e-03 2.1e-07 1.8e-02%
6000 3.82330e-04 6.1e-08 1.6e-02%
7000 1.78036e-04 2.7e-08 1.5e-02%
8000 9.91945e-05 1.9e-08 1.9e-02%
9000 6.05766e-05 1.6e-08 2.6e-02%
10000 3.92631e-05 1.2e-08 3.0e-02%

2 个答案:

答案 0 :(得分:1)

对于示例文件,您可以执行以下操作:

app.component.html

否则,我建议拆分以给每个集分配自己的文件,而不是使用pandas.read_csv读取它们。

答案 1 :(得分:0)

首先,定义一个将文件拆分为多个部分的函数。这是一个生成器,它生成一系列行列表:

def split_sections(infile):
    """Generate a sequence of lists of lines from infile delimited by blank lines.
    """
    section = []
    for line in infile:
        if not line.strip():
            if section:
                yield section
                section = []
        else:
            section.append(line)
    if section: # last section may not have blank line after it
        yield section

然后您的实际任务非常简单:

with open(path) as infile:
    for lines in split_sections(infile):
        heading = lines[0].rstrip()
        data = np.genfromtxt(lines[1:], usecols=[0,1])
        print(heading)
        print(data)